#!/usr/bin/env bash
# ============================================================
#  Lab21 Network Connect
#  Installs Tailscale (if needed) and connects to lab21 network
#  via Headscale + Authentik login.
#
#  Usage:
#    chmod +x connect-lab21.sh && ./connect-lab21.sh
#    -- or --
#    curl -fsSL https://.../connect-lab21.sh | bash
# ============================================================

set -e

HEADSCALE="https://headscale.lab21helpdesk.com"
DASHBOARD="https://dashboard.ts.lab21helpdesk.com"

# ── Colours ──────────────────────────────────────────────────
GREEN='\033[0;32m'
CYAN='\033[0;36m'
RED='\033[0;31m'
NC='\033[0m'

info()  { echo -e "${CYAN}[..] $*${NC}"; }
ok()    { echo -e "${GREEN}[OK] $*${NC}"; }
fail()  { echo -e "${RED}[ERROR] $*${NC}"; exit 1; }

echo -e "${GREEN}"
echo '  ██╗      █████╗ ██████╗  ██████╗  ██╗'
echo '  ██║     ██╔══██╗██╔══██╗╚════██╗███║'
echo '  ██║     ███████║██████╔╝  ████╔╝ ╚██║'
echo '  ██║     ██╔══██║██╔══██╗ ██╔═══╝  ██║'
echo '  ███████╗██║  ██║██████╔╝ ███████╗ ██║'
echo '  ╚══════╝╚═╝  ╚═╝╚═════╝  ╚═════╝  ╚═╝'
echo -e "${NC}"
echo -e "${CYAN}  Network Connect${NC}"
echo ""

# ── Detect OS ────────────────────────────────────────────────
OS="$(uname -s)"
case "$OS" in
    Darwin)  PLATFORM="macos" ;;
    Linux)   PLATFORM="linux" ;;
    *)       fail "Unsupported OS: $OS" ;;
esac

# ── Check internet connection ─────────────────────────────────
info "Checking internet connection..."
if ! curl -fsSL --max-time 5 --head https://pkgs.tailscale.com -o /dev/null 2>/dev/null; then
    fail "No internet connection. Please check your network and try again."
fi
ok "Internet connection OK."
echo ""

# ── Check / install Tailscale ────────────────────────────────
if command -v tailscale &>/dev/null; then
    ok "Tailscale already installed: $(tailscale version | head -1)"
    info "Checking for existing session..."
    if [ "$PLATFORM" = "linux" ]; then
        LOGOUT_CMD="sudo tailscale logout"
    else
        LOGOUT_CMD="tailscale logout"
    fi
    if $LOGOUT_CMD 2>/dev/null; then
        ok "Logged out existing session."
    else
        info "No active session — continuing."
    fi
else
    info "Installing Tailscale..."

    if [ "$PLATFORM" = "macos" ]; then
        # macOS — check for App Store version first
        TS_APP="/Applications/Tailscale.app/Contents/MacOS/Tailscale"
        if [ -x "$TS_APP" ]; then
            ok "Tailscale app found. Adding CLI alias..."
            alias tailscale="$TS_APP"
            export PATH="$(dirname $TS_APP):$PATH"
        else
            info "Downloading Tailscale PKG for macOS..."
            TMP=$(mktemp -d)
            curl -fsSL "https://pkgs.tailscale.com/stable/tailscale-latest.pkg" -o "$TMP/tailscale.pkg"
            sudo installer -pkg "$TMP/tailscale.pkg" -target /
            rm -rf "$TMP"
        fi
    else
        # Linux — official install script handles distro detection
        if [ "$(id -u)" -ne 0 ]; then
            info "Linux install requires sudo..."
            curl -fsSL https://tailscale.com/install.sh | sudo bash
        else
            curl -fsSL https://tailscale.com/install.sh | bash
        fi
    fi

    command -v tailscale &>/dev/null || fail "Tailscale install failed. Install manually: https://tailscale.com/download"
    ok "Tailscale installed."
fi

# ── Connect to lab21 Headscale ───────────────────────────────
echo ""
info "Connecting to lab21 network at $HEADSCALE ..."
echo ""
echo "  A browser window will open — sign in with your Authentik account."
echo "  If no browser opens, copy the URL printed below and open it manually."
echo ""

if [ "$PLATFORM" = "linux" ]; then
    sudo tailscale up --login-server "$HEADSCALE" --reset
else
    tailscale up --login-server "$HEADSCALE" --reset
fi

echo ""
info "Waiting for connection..."
sleep 4

echo ""
tailscale status || true
echo ""
ok "Done. You are now connected to the lab21 network."
echo "   Visit $DASHBOARD to get started."
echo ""
