# Source this from any shell to get panda_ssh / panda_mount / panda_status.
#   source /data/cameron/agents_stuff/agents/panda/connect.sh

# Load connection details (HOST, PORT, USER, PASSWORD, MOUNT_POINT).
PANDA_CONN_FILE="$(dirname "${BASH_SOURCE[0]}")/connection.txt"
if [ ! -f "$PANDA_CONN_FILE" ]; then
    echo "panda: connection.txt missing at $PANDA_CONN_FILE — ask Cameron for the current ngrok address." >&2
    return 1 2>/dev/null || exit 1
fi
# shellcheck disable=SC1090
. <(grep -E '^[A-Z_]+=' "$PANDA_CONN_FILE")

PANDA_SSH_OPTS=(
    -p "$PORT"
    -o StrictHostKeyChecking=accept-new
    -o UserKnownHostsFile=/dev/null
    -o LogLevel=ERROR
    -o ServerAliveInterval=30
)

panda_ssh() {
    if [ -n "$PASSWORD" ]; then
        sshpass -p "$PASSWORD" ssh "${PANDA_SSH_OPTS[@]}" "${USER}@${HOST}" "$@"
    else
        ssh "${PANDA_SSH_OPTS[@]}" "${USER}@${HOST}" "$@"
    fi
}

panda_status() {
    if mountpoint -q "$MOUNT_POINT" 2>/dev/null; then
        echo "panda mount: UP ($MOUNT_POINT)"
    else
        echo "panda mount: DOWN ($MOUNT_POINT not mounted)"
    fi
    echo -n "ssh test:    "
    if panda_ssh -o ConnectTimeout=5 'echo ok' 2>/dev/null | grep -q '^ok$'; then
        echo "OK ($USER@$HOST:$PORT)"
    else
        echo "FAILED ($USER@$HOST:$PORT)"
    fi
}

panda_mount() {
    mkdir -p "$MOUNT_POINT"
    if mountpoint -q "$MOUNT_POINT"; then
        echo "Already mounted at $MOUNT_POINT — unmounting first."
        fusermount3 -u "$MOUNT_POINT" || fusermount -u "$MOUNT_POINT"
    fi
    if [ -n "$PASSWORD" ]; then
        sshpass -p "$PASSWORD" sshfs \
            -p "$PORT" \
            -o StrictHostKeyChecking=accept-new \
            -o UserKnownHostsFile=/dev/null \
            -o password_stdin \
            -o reconnect \
            -o ServerAliveInterval=30 \
            -o ServerAliveCountMax=3 \
            "${USER}@${HOST}:/" "$MOUNT_POINT" <<<"$PASSWORD"
    else
        sshfs \
            -p "$PORT" \
            -o StrictHostKeyChecking=accept-new \
            -o UserKnownHostsFile=/dev/null \
            -o reconnect \
            -o ServerAliveInterval=30 \
            -o ServerAliveCountMax=3 \
            "${USER}@${HOST}:/" "$MOUNT_POINT"
    fi
    echo "Mounted ${USER}@${HOST}:/ at $MOUNT_POINT"
    ls "$MOUNT_POINT" 2>&1 | head
}

panda_unmount() {
    fusermount3 -u "$MOUNT_POINT" 2>/dev/null || fusermount -u "$MOUNT_POINT" 2>/dev/null
    echo "Unmounted $MOUNT_POINT"
}
