#!/bin/sh
# Expects a hostname and optionally a directory

# Connects to hostname by SSH
# Exports a local directory (default $HOME/tmp) over 9p-over-SSH
# Mounts that dir unter /mnt/term on the remote host, using 9pfs
# 
# Assumptions:
#   locally installed socat
#   locally installed u9fs
#   9pfs (https://github.com/ftrvxmtrx/9pfs.git) is installed on the remote host
#   username is identical on both machines
#   port 5565 is not locally or remotely bound by another process
#   remote user is allowed to call "doas 9pfs" or "sudo 9pfs" (see comment below)
#   both hosts have minimal IPv6, so that bind/connect on ::1 works
#   ssh-portforwarding works between the machines
# 

usage () {
    printf "Usage: %s host [path]" $0
    exit 1
}

if [ $# -lt 2 ]; then
    usage
fi

host=$1

# XXX doas-or-sudo: this should be detected automatically on the remote host...
SUDO=doas

# which directory to export
if [ $# -eq 2 ]; then
  if [ ! -d "$2" ]; then
      usage
  fi
  XPRT="$2"
else
  XPRT=$HOME/tmp
fi

killit() {
    echo "killing socat and background ssh"
    kill -9 $spid $pid
}

# cleanup on exit
trap killit EXIT

# Forward u9fs over-socat-over-SSH
socat TCP6-LISTEN:5565,bind=[::1] EXEC:"u9fs -u $USER -l /tmp/u9fs.log -a none $XPRT" & spid=$!

# mount u9fs as remote user on /mnt/term
# u9fs talks 9p on stdin/stdout. This connects it to port 5565 on localhost6
# XXX It should be possible to redirect stdin/stdout through ssh, but in my experiments
#     the remote 9pfs errored out with "tag mismatch")
# XXX Make 
ssh -R 5565:[::1]:5565 -n -X -M $host \
    "doas mkdir -p /mnt/term && $SUDO 9pfs -p 5565 -u $USER -o allow_other -f localhost /mnt/term" & pid=$!

sleep 5      # wait for mount to finish
ssh -X $host # throw in "-X" for good measure
