#!/usr/bin/env bash
# bash -c "$(wget -qLO- https://github.com/therepos/proxmox/raw/main/apps/setup-tailscale.sh?$(date +%s))"
# Purpose: Install / Update / Uninstall Tailscale subnet router LXC on Proxmox
# =============================================================================

set -euo pipefail

# --- Helpers -----------------------------------------------------------------
# >>> admonition
if [[ -n "${FORCE_COLOR:-}" || -t 1 ]]; then
  _CK=$'\033[1;32m'; _CI=$'\033[1;36m'; _CW=$'\033[1;33m'; _CE=$'\033[1;31m'; _C0=$'\033[0m'
else
  _CK=''; _CI=''; _CW=''; _CE=''; _C0=''
fi
ok()   { printf '%s[ OK ]%s %s\n' "$_CK" "$_C0" "$*"; }
info() { printf '%s[INFO]%s %s\n' "$_CI" "$_C0" "$*"; }
warn() { printf '%s[WARN]%s %s\n' "$_CW" "$_C0" "$*" >&2; }
fail() { printf '%s[FAIL]%s %s\n' "$_CE" "$_C0" "$*" >&2; exit 1; }
banner() { local l='================================================='; printf '\n%s\n  %s\n%s\n' "$l" "$*" "$l"; }
# Status line: value red when missing/failed, yellow while starting, green when OK.
row() {
  local c=''
  case "${2,,}" in
    not|*"not "*|*not-*|*missing*|*fail*|*error*|*inactive*|*disconnected*) c="$_CE" ;;
    *activating*|*reconnecting*|*starting*) c="$_CW" ;;
    *installed*|*active*|*connected*|*"logged in"*|*running*|*enabled*|*mounted*|*loaded*) c="$_CK" ;;
  esac
  printf '  %-16s%s%s%s\n' "$1" "$c" "$2" "${c:+$_C0}"
}
# <<< admonition
# >>> menu
menu() {
  local o name desc i=1 w=0 pick
  { true </dev/tty; } 2>/dev/null || { warn "No terminal for the menu."; exit 0; }
  for o in "$@"; do name="${o%%|*}"; (( ${#name} > w )) && w=${#name}; done
  echo ""
  for o in "$@"; do
    name="${o%%|*}"; desc=""; [[ "$o" == *"|"* ]] && desc="${o#*|}"
    if [[ -n "$desc" ]]; then printf '  %d) %-*s  %s\n' "$i" "$w" "$name" "$desc"
    else printf '  %d) %s\n' "$i" "$name"; fi
    i=$((i + 1))
  done
  echo "  0) Exit"
  echo ""
  while true; do
    read -rp "  Choose [0-$#]: " pick </dev/tty || exit 0
    [[ "$pick" == "0" ]] && exit 0
    if [[ "$pick" =~ ^[0-9]+$ ]] && (( pick >= 1 && pick <= $# )); then
      CHOICE="${!pick}"; CHOICE="${CHOICE%%|*}"; return 0
    fi
    warn "Choose a number from 0 to $#."
  done
}
# <<< menu

[[ $EUID -eq 0 ]] || fail "Run as root."

CYAN="\e[36m"
RESET="\e[0m"

# Back-compat wrapper used within this script:
status_message() {
    case "$1" in
        success) ok "$2" ;;
        info)    info "$2" ;;
        *)       fail "$2" ;;   # error → print + exit
    esac
}

# --- Config ------------------------------------------------------------------
HOSTNAME="tailscale"
CTID_DEFAULT=100
MEMORY=512
CORES=1
DISK=2
STORAGE="local-lvm"
TEMPLATE_STORAGE="local"
BRIDGE="vmbr0"

# --- Shared helpers ----------------------------------------------------------
# jq runs on the Proxmox host (parsing JSON piped out of the container),
# so the container itself never needs it. Install on demand if absent.
ensure_jq() {
    if command -v jq &>/dev/null; then
        return 0
    fi
    info "Installing jq (required to check route status)..."
    if apt-get install -y -qq jq >/dev/null 2>&1; then
        ok "jq installed."
    else
        warn "Could not install jq; skipping route check."
        return 1
    fi
}

print_subnet_instructions() {
    local subnet="$1"
    echo ""
    echo -e "${CYAN}=============================================="
    echo "  Enable Subnet Routing"
    echo -e "==============================================${RESET}"
    echo ""
    echo "  1. Go to https://login.tailscale.com/admin/machines"
    echo "  2. Find '$HOSTNAME' -> ... -> Edit route settings"
    echo "  3. Tick $subnet and Save"
    echo ""
    echo "  Reach any LAN device from your tailnet at its normal IP,"
    echo "  e.g. <device-ip>:8080"
    echo ""
}

# --- Precheck ----------------------------------------------------------------
if ! command -v pct &> /dev/null; then
    status_message "error" "pct not found. Run this on the Proxmox host."
fi

# Find existing CTID (if installed)
find_ctid() {
    for id in $(pct list | awk 'NR>1 {print $1}'); do
        if pct config "$id" 2>/dev/null | grep -qx "hostname: ${HOSTNAME}"; then
            echo "$id"
            return
        fi
    done
}

EXISTING_CTID=$(find_ctid)

# --- Actions -----------------------------------------------------------------

action_install() {
    if [[ -n "$EXISTING_CTID" ]]; then
        echo "Existing LXC found at CTID $EXISTING_CTID. Will be removed first."
        read -p "Continue? [y/N]: " confirm </dev/tty
        if [[ ! "$confirm" =~ ^[Yy]$ ]]; then
            status_message "info" "Cancelled."
            exit 0
        fi
        action_uninstall_silent
    fi

    # Pick free CTID
    # nextid checks VMs and containers cluster-wide (pct status only sees containers)
    local ctid
    ctid=$(pvesh get /cluster/nextid --vmid "$CTID_DEFAULT" 2>/dev/null) \
        || ctid=$(pvesh get /cluster/nextid)
    status_message "info" "Using CTID $ctid"

    # Detect subnet
    local lan_subnet
    lan_subnet=$(ip -4 route show dev "$BRIDGE" proto kernel scope link 2>/dev/null \
        | awk '{print $1}' | head -1)
    if [[ -z "$lan_subnet" || ! "$lan_subnet" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+/[0-9]+$ ]]; then
        status_message "error" "Could not detect subnet from $BRIDGE."
    fi
    status_message "info" "Detected LAN subnet: $lan_subnet"

    # Template
    pveam update >/dev/null
    local template
    template=$(pveam available --section system | awk '/debian-12-standard/ {print $2}' | sort -V | tail -1)
    if [[ -z "$template" ]]; then
        status_message "error" "No Debian 12 template found."
    fi
    if ! pveam list "$TEMPLATE_STORAGE" | grep -q "$template"; then
        status_message "info" "Downloading template..."
        pveam download "$TEMPLATE_STORAGE" "$template" >/dev/null
    fi

    local lxc_password
    lxc_password=$(openssl rand -base64 16)

    status_message "info" "Creating LXC..."
    pct create "$ctid" "${TEMPLATE_STORAGE}:vztmpl/${template}" \
        --timezone host \
        --hostname "$HOSTNAME" \
        --cores "$CORES" --memory "$MEMORY" --swap "$MEMORY" \
        --net0 "name=eth0,bridge=${BRIDGE},ip=dhcp" \
        --rootfs "${STORAGE}:${DISK}" \
        --unprivileged 1 --features nesting=1 --onboot 1 \
        --password "$lxc_password" >/dev/null

    (umask 077; printf '%s\n' "$lxc_password" > "/root/.tailscale-lxc-${ctid}.pw")

    # TUN device
    cat >> "/etc/pve/lxc/${ctid}.conf" <<EOF
lxc.cgroup2.devices.allow: c 10:200 rwm
lxc.mount.entry: /dev/net/tun dev/net/tun none bind,create=file
EOF

    pct start "$ctid"
    info "Waiting for the container network..."
    for _ in $(seq 1 30); do
        pct exec "$ctid" -- getent hosts tailscale.com &>/dev/null && break
        sleep 2
    done
    pct exec "$ctid" -- getent hosts tailscale.com &>/dev/null \
        || fail "Container has no network/DNS after 60s (CTID $ctid)."

    status_message "info" "Installing Tailscale..."
    pct exec "$ctid" -- bash -c "
        set -e
        export LC_ALL=C
        export LANG=C
        echo 'LC_ALL=C' > /etc/default/locale
        apt update -qq >/dev/null 2>&1
        apt install -y -qq curl >/dev/null 2>&1
        curl -fsSL https://tailscale.com/install.sh | sh >/dev/null 2>&1
        echo 'net.ipv4.ip_forward = 1' >> /etc/sysctl.conf
        echo 'net.ipv6.conf.all.forwarding = 1' >> /etc/sysctl.conf
        sysctl -p >/dev/null
        tailscale set --auto-update >/dev/null 2>&1 || true
    " || fail "Tailscale install failed inside CTID $ctid. Check: pct enter $ctid"
    status_message "success" "Tailscale installed."

    # Auth
    echo ""
    echo -e "${CYAN}=============================================="
    echo "  Open the URL below in your browser to log in:"
    echo -e "==============================================${RESET}"
    pct exec "$ctid" -- tailscale up --advertise-routes="$lan_subnet" --accept-routes

    echo ""
    status_message "success" "Setup complete (CTID $ctid, subnet $lan_subnet)."
    print_subnet_instructions "$lan_subnet"
}

action_update() {
    if [[ -z "$EXISTING_CTID" ]]; then
        status_message "error" "No Tailscale LXC installed."
    fi
    status_message "info" "Updating Tailscale in CTID $EXISTING_CTID..."
    pct exec "$EXISTING_CTID" -- bash -c "
        export LC_ALL=C
        apt update -qq >/dev/null 2>&1
        apt install -y -qq --only-upgrade tailscale
    "
    local version
    version=$(pct exec "$EXISTING_CTID" -- tailscale version | head -1)
    status_message "success" "Tailscale updated. Version: $version"
}

action_uninstall_silent() {
    if [[ -n "$EXISTING_CTID" ]]; then
        pct stop "$EXISTING_CTID" 2>/dev/null || true
        pct destroy "$EXISTING_CTID" --purge 2>/dev/null
        rm -f "/root/.tailscale-lxc-${EXISTING_CTID}.pw"
    fi
}

action_uninstall() {
    if [[ -z "$EXISTING_CTID" ]]; then
        status_message "error" "No Tailscale LXC installed."
    fi
    echo "This will permanently destroy LXC $EXISTING_CTID and remove it from Tailscale."
    read -p "Type 'yes' to confirm: " confirm </dev/tty
    if [[ "$confirm" != "yes" ]]; then
        status_message "info" "Cancelled."
        exit 0
    fi
    status_message "info" "Logging out of Tailscale..."
    pct exec "$EXISTING_CTID" -- tailscale logout 2>/dev/null || true
    status_message "info" "Destroying LXC $EXISTING_CTID..."
    action_uninstall_silent
    status_message "success" "Tailscale LXC removed."
    echo ""
    echo "  Also remove the device from https://login.tailscale.com/admin/machines"
}

action_status() {
    if [[ -z "$EXISTING_CTID" ]]; then
        status_message "info" "Tailscale LXC: not installed"
        return
    fi

    local state ip
    state=$(pct status "$EXISTING_CTID" | awk '{print $2}')
    ip=$(pct exec "$EXISTING_CTID" -- ip route get 1.1.1.1 2>/dev/null \
         | grep -oP 'src \K\S+' || true)

    echo ""
    echo "LXC $EXISTING_CTID status:"
    echo "${ip:-(no ip)}  ${state}"

    echo ""
    echo "Tailscale status:"
    pct exec "$EXISTING_CTID" -- tailscale status 2>/dev/null \
        || echo "  (LXC not running or tailscale not authenticated)"

    echo ""
    echo "Tailscale version:"
    pct exec "$EXISTING_CTID" -- tailscale version 2>/dev/null | head -1 || true

    # --- Subnet route approval check ---
    echo ""
    echo "Subnet route:"

    if ! ensure_jq; then
        return
    fi

    local json advertised approved
    json=$(pct exec "$EXISTING_CTID" -- tailscale status --json 2>/dev/null || true)

    if [[ -z "$json" ]]; then
        warn "Could not query tailscale (LXC stopped or not authenticated)"
        return
    fi

    # Routes this node offers, minus the auto-added /32 and /128 self-routes
    advertised=$(echo "$json" | jq -r '
        (.Self.AllowedIPs // [])
        - (.Self.TailscaleIPs // [] | map(. + "/32", . + "/128"))
        | .[]' 2>/dev/null | grep -v '^$' || true)

    if [[ -z "$advertised" ]]; then
        info "No subnet routes advertised"
        return
    fi

    approved=$(echo "$json" | jq -r '.Self.PrimaryRoutes // [] | .[]' 2>/dev/null || true)

    local pending=0 route
    local LAST_PENDING_ROUTE=""
    while IFS= read -r route; do
        [[ -z "$route" ]] && continue
        if echo "$approved" | grep -qx "$route"; then
            ok "$route (approved)"
        else
            warn "$route advertised but NOT approved"
            pending=1
            LAST_PENDING_ROUTE="$route"
        fi
    done <<< "$advertised"

    if [[ "$pending" -eq 1 ]]; then
        print_subnet_instructions "$LAST_PENDING_ROUTE"
    fi
}

# --- Menu --------------------------------------------------------------------

banner "Tailscale LXC Manager"
echo ""
if [[ -n "$EXISTING_CTID" ]]; then
    ok "Installed (CTID $EXISTING_CTID)"
else
    info "Not installed"
fi

menu "Install / Reinstall" "Update Tailscale" "Uninstall" "Show status"
echo ""

case "$CHOICE" in
    "Install / Reinstall") action_install ;;
    "Update Tailscale")    action_update ;;
    "Uninstall")           action_uninstall ;;
    "Show status")         action_status ;;
esac
