#!/bin/sh
set -eu

usage() {
    echo "usage: $0 <host> [port|done]   (default port 8443)" >&2
    exit "${1:-1}"
}

case "${1:-}" in
    -h|--help|help) usage 0 ;;
    "") echo "error: missing host" >&2; usage 1 ;;
esac

host=$1
arg=${2:-8443}
server=${host#*@}
dir=${XDG_RUNTIME_DIR:-/tmp}/incus-tunnel
mkdir -p "$dir"

if [ "$arg" = done ]; then
    n=0
    for sock in "$dir/$server"-*; do
        [ -S "$sock" ] || continue
        n=$((n + 1))
        ssh -S "$sock" -O exit "$host" >/dev/null 2>&1 || rm -f "$sock"
    done
    [ "$n" -gt 0 ] || { echo "no tunnel for $server" >&2; exit 1; }
    exit 0
fi

case $arg in
    *[!0-9]*) echo "error: port must be numeric or 'done'" >&2; usage 1 ;;
esac

sock=$dir/$server-$arg
if [ -S "$sock" ] && ssh -S "$sock" -O check "$host" >/dev/null 2>&1; then
    echo "already up: $server :$arg"
    exit 0
fi
rm -f "$sock"

ip=$(ssh "$host" 'set -- $SSH_CONNECTION; printf %s "$3"')
[ -n "$ip" ] || { echo "error: no address for $server" >&2; exit 1; }
case $ip in *:*) dest="[$ip]" ;; *) dest=$ip ;; esac

incus remote switch "$server"
ssh -f -N -M -S "$sock" -o ExitOnForwardFailure=yes -L "$arg:$dest:$arg" "$host"
echo "up: $server :$arg -> $dest"
