#!/bin/bash
set -euo pipefail

usage() {
    cat <<'USAGE'
Usage: scripts/haicore_sshfs.sh <command> [options]

Commands:
  open      Open SSH master connection (OTP/password once, then persist)
  mount     Mount remote path via sshfs using existing master (fail-closed)
  umount    Unmount sshfs mountpoint
  status    Show master/mount status
  close     Close SSH master connection

Options:
  --host <HOST>           SSH target host or alias (default: $HAICORE_HOST or haicore)
  --socket <PATH>         Control socket path (default: $HAICORE_SOCKET or ~/.ssh/cm-haicore.sock)
  --persist <DURATION>    SSH ControlPersist value (default: $HAICORE_CONTROL_PERSIST or 8h)
  --remote-path <PATH>    Remote path to mount (default: $HAICORE_REMOTE_PATH or /home/kastel/vy3326)
  --mount-dir <PATH>      Local mountpoint (default: $HAICORE_MOUNT_DIR or ~/mnt/haicore)
  --volume-name <NAME>    macOS Finder volume label (default: $HAICORE_VOLUME_NAME or haicore-home)
  --help, -h              Show this message

Examples:
  # 1) Authenticate once (OTP/password)
  scripts/haicore_sshfs.sh open --host <user>@haicore.scc.kit.edu

  # 2) Mount home path with no interactive auth fallback
  scripts/haicore_sshfs.sh mount --remote-path /home/kastel/vy3326

  # 3) Check status / clean up
  scripts/haicore_sshfs.sh status
  scripts/haicore_sshfs.sh umount
  scripts/haicore_sshfs.sh close

Notes:
  - 'mount' uses BatchMode=yes through the control socket to avoid OTP spam.
  - It also overrides host RemoteCommand/TTY settings for SFTP compatibility.
  - If the control socket is stale, 'mount' refreshes the master and retries once.
  - If the master connection dies, 'mount' fails immediately instead of reauthing.
USAGE
}

die() {
    echo "ERROR: $*" >&2
    exit 1
}

have_cmd() {
    command -v "$1" >/dev/null 2>&1
}

is_mounted() {
    local target
    target="$1"
    if have_cmd mountpoint; then
        mountpoint -q "$target"
        return $?
    fi
    mount | grep -F " on ${target} " >/dev/null 2>&1
}

ssh_master_up() {
    ssh \
        -S "$SOCKET" \
        -o RemoteCommand=none \
        -o RequestTTY=no \
        -O check \
        "$HOST" >/dev/null 2>&1
}

ssh_master_channel_ok() {
    ssh \
        -S "$SOCKET" \
        -o BatchMode=yes \
        -o ConnectionAttempts=1 \
        -o ConnectTimeout=8 \
        -o RemoteCommand=none \
        -o RequestTTY=no \
        "$HOST" \
        -- true >/dev/null 2>&1
}

cmd_open() {
    have_cmd ssh || die "'ssh' not found."
    mkdir -p "$(dirname "$SOCKET")"

    if ssh_master_up; then
        echo "SSH master already active for '$HOST' (socket: $SOCKET)"
        return 0
    fi

    echo "Opening SSH master for '$HOST'..."
    echo "You may be prompted once for OTP/password."
    ssh \
        -M \
        -N \
        -f \
        -S "$SOCKET" \
        -o ControlMaster=yes \
        -o ControlPath="$SOCKET" \
        -o ControlPersist="$CONTROL_PERSIST" \
        -o RemoteCommand=none \
        -o RequestTTY=no \
        "$HOST"

    ssh_master_up || die "SSH master did not come up. Check host/auth settings."
    echo "SSH master active (persist=${CONTROL_PERSIST})."
}

run_sshfs_mount() {
    local -a sshfs_cmd

    sshfs_cmd=(
        sshfs
        "${HOST}:${REMOTE_PATH}"
        "$MOUNT_DIR"
        -o "ssh_command=ssh -S $SOCKET -o BatchMode=yes -o ConnectionAttempts=1 -o ConnectTimeout=8 -o RemoteCommand=none -o RequestTTY=no"
        -o ServerAliveInterval=30
        -o ServerAliveCountMax=3
    )

    if [[ "$(uname -s)" == "Darwin" ]]; then
        sshfs_cmd+=(-o "volname=${VOLUME_NAME}")
    fi

    "${sshfs_cmd[@]}"
}

refresh_master_connection() {
    echo "Refreshing SSH master connection for '$HOST'..."
    if ssh_master_up; then
        ssh \
            -S "$SOCKET" \
            -o RemoteCommand=none \
            -o RequestTTY=no \
            -O exit \
            "$HOST" >/dev/null 2>&1 || true
    fi
    if [[ -S "$SOCKET" ]]; then
        rm -f "$SOCKET"
    fi
    cmd_open
}

cmd_mount() {
    have_cmd ssh || die "'ssh' not found."
    have_cmd sshfs || die "'sshfs' not found. Install macFUSE+sshfs (macOS) or sshfs package (Linux)."

    ssh_master_up || die "No active SSH master found. Run: scripts/haicore_sshfs.sh open"

    if ! ssh_master_channel_ok; then
        echo "Detected stale SSH master (control socket exists, channel open failed)."
        refresh_master_connection
    fi

    mkdir -p "$MOUNT_DIR"

    if is_mounted "$MOUNT_DIR"; then
        echo "Already mounted: $MOUNT_DIR"
        return 0
    fi

    echo "Mounting '$HOST:$REMOTE_PATH' -> '$MOUNT_DIR'..."
    if ! run_sshfs_mount; then
        echo "Mount failed on first attempt. Retrying once with a refreshed master..."
        refresh_master_connection
        run_sshfs_mount || die "Mount failed after retry. Check host path and server-side SFTP availability."
    fi

    is_mounted "$MOUNT_DIR" || die "Mount command returned but mount not detected."
    echo "Mounted: $MOUNT_DIR"
}

cmd_umount() {
    if ! is_mounted "$MOUNT_DIR"; then
        echo "Mount not active: $MOUNT_DIR"
        return 0
    fi

    echo "Unmounting '$MOUNT_DIR'..."
    if have_cmd fusermount && fusermount -u "$MOUNT_DIR" >/dev/null 2>&1; then
        :
    elif have_cmd umount && umount "$MOUNT_DIR" >/dev/null 2>&1; then
        :
    elif have_cmd diskutil && diskutil unmount "$MOUNT_DIR" >/dev/null 2>&1; then
        :
    else
        die "Failed to unmount (tried fusermount/umount/diskutil)."
    fi
    echo "Unmounted: $MOUNT_DIR"
}

cmd_status() {
    echo "Host:        $HOST"
    echo "Socket:      $SOCKET"
    echo "Mount dir:   $MOUNT_DIR"
    echo "Remote path: $REMOTE_PATH"
    echo "Volume name: $VOLUME_NAME"
    echo "Persist:     $CONTROL_PERSIST"

    if ssh_master_up; then
        echo "Master:      active"
    else
        echo "Master:      inactive"
    fi

    if is_mounted "$MOUNT_DIR"; then
        echo "Mount:       active"
    else
        echo "Mount:       inactive"
    fi
}

cmd_close() {
    have_cmd ssh || die "'ssh' not found."

    if is_mounted "$MOUNT_DIR"; then
        echo "WARNING: mount is still active at $MOUNT_DIR"
        echo "         Run: scripts/haicore_sshfs.sh umount"
    fi

    if ssh_master_up; then
        echo "Closing SSH master for '$HOST'..."
        ssh \
            -S "$SOCKET" \
            -o RemoteCommand=none \
            -o RequestTTY=no \
            -O exit \
            "$HOST" >/dev/null
        echo "SSH master closed."
    else
        echo "SSH master already inactive."
    fi

    if [[ -S "$SOCKET" ]]; then
        rm -f "$SOCKET"
    fi
}

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

COMMAND="$1"
shift

HOST="${HAICORE_HOST:-haicore}"
SOCKET="${HAICORE_SOCKET:-$HOME/.ssh/cm-haicore.sock}"
CONTROL_PERSIST="${HAICORE_CONTROL_PERSIST:-8h}"
REMOTE_PATH="${HAICORE_REMOTE_PATH:-/home/kastel/vy3326}"
MOUNT_DIR="${HAICORE_MOUNT_DIR:-$HOME/mnt/haicore}"
VOLUME_NAME="${HAICORE_VOLUME_NAME:-haicore-home}"

while [[ $# -gt 0 ]]; do
    case "$1" in
        --host)
            HOST="$2"
            shift 2
            ;;
        --socket)
            SOCKET="$2"
            shift 2
            ;;
        --persist)
            CONTROL_PERSIST="$2"
            shift 2
            ;;
        --remote-path)
            REMOTE_PATH="$2"
            shift 2
            ;;
        --mount-dir)
            MOUNT_DIR="$2"
            shift 2
            ;;
        --volume-name)
            VOLUME_NAME="$2"
            shift 2
            ;;
        --help|-h)
            usage
            exit 0
            ;;
        *)
            die "Unknown option: $1"
            ;;
    esac
done

case "$COMMAND" in
    open)
        cmd_open
        ;;
    mount)
        cmd_mount
        ;;
    umount|unmount)
        cmd_umount
        ;;
    status)
        cmd_status
        ;;
    close)
        cmd_close
        ;;
    --help|-h|help)
        usage
        ;;
    *)
        die "Unknown command: $COMMAND"
        ;;
esac
