#!/bin/sh
set -eu

usage() {
    cat <<'EOF'
Usage: sshfs-remote [-h] <host> <local-path> <remote-mountpoint>

Reverse-mount local-path onto host at remote-mountpoint.
Pipes a local sftp-server through ssh into remote sshfs (-o slave).

Remote needs sshfs, fuse, and a mountpoint you can write.
allow_other needs user_allow_other in the remote /etc/fuse.conf.
EOF
}

die() {
    echo "sshfs-remote: $*" >&2
    exit 1
}

case "${1:-}" in
    -h|--help) usage; exit 0 ;;
esac

if [ "$#" -ne 3 ]; then
    usage >&2
    exit 2
fi

host=$1
local_mount=$2
remote_mount=$3

command -v dpipe >/dev/null || die "dpipe not found (install moreutils)"
command -v ssh >/dev/null || die "ssh not found"

sftp=
for candidate in /usr/lib/ssh/sftp-server /usr/lib/openssh/sftp-server /usr/libexec/openssh/sftp-server; do
    if [ -x "$candidate" ]; then
        sftp=$candidate
        break
    fi
done
[ -n "$sftp" ] || die "sftp-server not found (openssh)"
[ -n "$host" ] || die "host is empty"
[ -d "$local_mount" ] || die "local path is not a directory: $local_mount"
case "$remote_mount" in
    /*) ;;
    *) die "remote mountpoint must be absolute: $remote_mount" ;;
esac

# ponytail: single-quote remote paths; breaks if a path contains '
exec dpipe "$sftp" = ssh -o ServerAliveInterval=14 -o ServerAliveCountMax=3 "$host" \
    "sshfs ':$local_mount' '$remote_mount' -f -o ro,slave,allow_other"
