#!/usr/bin/env bash
# sshp ("SSH PLUS") from lackadaisical

mounts=()
ssh_args=()
remote_port=$((10000 + RANDOM % 10000))
local_user=$(whoami)

usage() {
    echo "Usage: sshp -m <local>:<remote> [user@]host [ssh_options]"
    exit 1
}

while [[ $# -gt 0 ]]; do
    case "$1" in
        -m)
            if [[ -z "$2" ]]; then echo "Error: -m requires argument"; exit 1; fi
            mounts+=("$2")
            shift 2
            ;;
        *)
            ssh_args+=("$1")
            shift
            ;;
    esac
done

[[ ${#ssh_args[@]} -eq 0 ]] && usage

mount_logic=""
unmount_logic=""

for map in "${mounts[@]}"; do
    local_path="${map%%:*}"
    remote_path="${map##*:}"
    [[ "$local_path" != /* ]] && local_path="$PWD/$local_path"

    mount_logic+="
    echo '>> Preparing mount: ${remote_path}';
    mkdir -p \"${remote_path}\" 2>/dev/null || sudo mkdir -p \"${remote_path}\"

    sshfs -p ${remote_port} -o StrictHostKeyChecking=no,idmap=user ${local_user}@localhost:\"${local_path}\" \"${remote_path}\" 2>/dev/null || \
    sudo sshfs -p ${remote_port} -o StrictHostKeyChecking=no,idmap=user,allow_other ${local_user}@localhost:\"${local_path}\" \"${remote_path}\"
    "
    unmount_logic+="fusermount -u -z \"${remote_path}\" 2>/dev/null || sudo fusermount -u -z \"${remote_path}\" 2>/dev/null;"
done

remote_script="
    if ! command -v sshfs >/dev/null 2>&1; then
        echo 'WARNING: \"sshfs\" not found on remote host.'
    else
        ${mount_logic}
    fi
    \${SHELL:-bash};
    ${unmount_logic}
"

ssh -t -R ${remote_port}:localhost:22 "${ssh_args[@]}" "$remote_script"
