#!/usr/bin/env bash

set -euo pipefail

STATE_DIR="${STATE_DIR:-/var/lib/tower-tunnels}"
RUNTIME_DIR="${RUNTIME_DIR:-/run/tower-tunnels}"
LOG_DIR="${LOG_DIR:-/var/log/tower-tunnels}"
DEFAULT_SSH_USER="${DEFAULT_SSH_USER:-dPG}"
DEFAULT_PRIVATE_KEY="${DEFAULT_PRIVATE_KEY:-/home/dPG/.ssh/fuse/id_rsa}"
DEFAULT_KNOWN_HOSTS_FILE="${DEFAULT_KNOWN_HOSTS_FILE:-/root/.ssh/known_hosts}"
DEFAULT_PRINTER_PORT="${DEFAULT_PRINTER_PORT:-8080}"

usage() {
    cat <<'EOF'
Usage:
  sudo ./tower-tunnel-control status
  sudo ./tower-tunnel-control restart <instance_name>
  sudo ./tower-tunnel-control restart-all

Commands:
  status       Show known tower tunnels and whether their ssh process is running
  restart      Restart one existing tunnel using its saved metadata
  restart-all  Restart every existing tunnel using saved metadata
EOF
}

for cmd in ssh systemd-escape setsid; do
    command -v "$cmd" >/dev/null 2>&1 || {
        echo "ERROR: Required command '$cmd' is not installed or not in PATH."
        exit 1
    }
done

is_pid_running() {
    local pid="$1"
    [[ -n "$pid" ]] && kill -0 "$pid" 2>/dev/null
}

instance_id_for() {
    systemd-escape -- "$1"
}

load_meta() {
    local instance_id="$1"
    local meta_file="$STATE_DIR/${instance_id}.meta"

    if [[ ! -f "$meta_file" ]]; then
        echo "ERROR: No saved metadata for ${instance_id}."
        exit 1
    fi

    # shellcheck disable=SC1090
    source "$meta_file"
}

stop_instance() {
    local instance_id="$1"
    local pid_file="$RUNTIME_DIR/${instance_id}.pid"
    local pid=''

    if [[ -f "$pid_file" ]]; then
        pid="$(<"$pid_file")"
        if is_pid_running "$pid"; then
            kill "$pid" 2>/dev/null || true
            for _ in $(seq 1 10); do
                if ! is_pid_running "$pid"; then
                    break
                fi
                sleep 1
            done
            if is_pid_running "$pid"; then
                kill -9 "$pid" 2>/dev/null || true
            fi
        fi
    fi

    rm -f "$pid_file"
}

start_instance() {
    local instance_id="$1"
    load_meta "$instance_id"

    local pid_file="$RUNTIME_DIR/${instance_id}.pid"
    local log_file="$LOG_DIR/${instance_id}.log"

    mkdir -p "$RUNTIME_DIR" "$LOG_DIR"
    : >"$log_file"
    chmod 0600 "$log_file"

    setsid /usr/bin/ssh \
        -i "$DEFAULT_PRIVATE_KEY" \
        -N \
        -T \
        -L "127.0.0.1:${LOCAL_PORT}:${PRINTER_HOST}:${DEFAULT_PRINTER_PORT}" \
        -o UserKnownHostsFile="${DEFAULT_KNOWN_HOSTS_FILE}" \
        -o StrictHostKeyChecking=accept-new \
        -o ExitOnForwardFailure=yes \
        -o ServerAliveInterval=30 \
        -o ServerAliveCountMax=3 \
        "${DEFAULT_SSH_USER}@${SSH_HOST}" >>"$log_file" 2>&1 &

    echo "$!" >"$pid_file"
    chmod 0600 "$pid_file"
    echo "Restarted ${INSTANCE_NAME} on localhost:${LOCAL_PORT}"
}

status_all() {
    for meta_file in "$STATE_DIR"/*.meta; do
        [[ -e "$meta_file" ]] || {
            echo "No saved tower tunnel metadata found."
            return 0
        }

        instance_id="$(basename "$meta_file" .meta)"
        load_meta "$instance_id"

        pid_file="$RUNTIME_DIR/${instance_id}.pid"
        status="stopped"
        pid=''

        if [[ -f "$pid_file" ]]; then
            pid="$(<"$pid_file")"
            if is_pid_running "$pid"; then
                status="running"
            fi
        fi

        printf '%s\t%s\t%s\t%s\t%s\n' \
            "$INSTANCE_NAME" \
            "$status" \
            "${pid:-}" \
            "$LOCAL_PORT" \
            "$SSH_HOST"
    done
}

restart_one() {
    local instance_name="$1"
    local instance_id
    instance_id="$(instance_id_for "$instance_name")"
    stop_instance "$instance_id"
    start_instance "$instance_id"
}

restart_all() {
    for meta_file in "$STATE_DIR"/*.meta; do
        [[ -e "$meta_file" ]] || {
            echo "No saved tower tunnel metadata found."
            return 0
        }

        instance_id="$(basename "$meta_file" .meta)"
        stop_instance "$instance_id"
        start_instance "$instance_id"
    done
}

case "${1:-}" in
    status)
        [[ $# -eq 1 ]] || { usage; exit 1; }
        status_all
        ;;
    restart)
        [[ $# -eq 2 ]] || { usage; exit 1; }
        restart_one "$2"
        ;;
    restart-all)
        [[ $# -eq 1 ]] || { usage; exit 1; }
        restart_all
        ;;
    -h|--help|'')
        usage
        ;;
    *)
        echo "ERROR: Unknown command '$1'."
        usage
        exit 1
        ;;
esac
