#!/bin/bash
# =============================================================
# Headscale VPN Join Script
# Server: https://head.webfactor.com
# MagicDNS: *.webfactor.internal
# =============================================================
#
# Usage:
#   curl -sL https://head.webfactor.com/join.sh | sudo bash -s -- <hostname>
#   OR
#   sudo bash join-network.sh <hostname>
#
# Example:
#   sudo bash join-network.sh s14
#   sudo bash join-network.sh laptop-alex
#   sudo bash join-network.sh office-pc
#
# After joining, the machine will be accessible as:
#   <hostname>.webfactor.internal
# =============================================================

set -euo pipefail

HEADSCALE_URL="https://head.webfactor.com"
HOSTNAME="${1:-}"

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

if [ -z "$HOSTNAME" ]; then
    echo -e "${RED}Error: Hostname is required${NC}"
    echo "Usage: $0 <hostname>"
    echo "Example: $0 s14"
    exit 1
fi

if [ "$(id -u)" -ne 0 ]; then
    echo -e "${RED}Error: This script must be run as root (use sudo)${NC}"
    exit 1
fi

echo -e "${GREEN}=== Headscale VPN Join Script ===${NC}"
echo -e "Server: ${HEADSCALE_URL}"
echo -e "Hostname: ${HOSTNAME}"
echo ""

# Detect OS
if [ -f /etc/os-release ]; then
    . /etc/os-release
    OS=$ID
else
    echo -e "${RED}Cannot detect OS${NC}"
    exit 1
fi

echo -e "${YELLOW}[1/4] Installing Tailscale client...${NC}"

if command -v tailscale &>/dev/null; then
    echo "Tailscale already installed: $(tailscale version | head -1)"
else
    case "$OS" in
        debian|ubuntu|linuxmint|pop)
            curl -fsSL https://tailscale.com/install.sh | sh
            ;;
        fedora|centos|rhel|rocky|alma)
            curl -fsSL https://tailscale.com/install.sh | sh
            ;;
        arch|manjaro)
            pacman -Sy --noconfirm tailscale
            ;;
        alpine)
            apk add tailscale
            ;;
        *)
            echo -e "${YELLOW}Unknown OS '$OS', trying universal install...${NC}"
            curl -fsSL https://tailscale.com/install.sh | sh
            ;;
    esac
fi

echo -e "${YELLOW}[2/4] Starting tailscaled service...${NC}"
systemctl enable --now tailscaled 2>/dev/null || service tailscaled start 2>/dev/null || true
sleep 2

echo -e "${YELLOW}[3/4] Connecting to Headscale...${NC}"
echo ""
echo -e "${YELLOW}You need an auth key from the Headscale server.${NC}"
echo "Generate one on s13 with:"
echo "  docker exec headscale headscale preauthkeys create --user 1 --reusable --expiration 1h"
echo ""

if [ -n "${AUTHKEY:-}" ]; then
    echo "Using provided AUTHKEY..."
else
    read -rp "Enter auth key: " AUTHKEY
fi

if [ -z "$AUTHKEY" ]; then
    echo -e "${RED}Error: Auth key is required${NC}"
    exit 1
fi

# Remove immutable flag on resolv.conf if present (common on VPS)
if lsattr /etc/resolv.conf 2>/dev/null | grep -q 'i'; then
    echo "Removing immutable flag from /etc/resolv.conf for MagicDNS..."
    chattr -i /etc/resolv.conf
fi

# Logout first if already connected somewhere
tailscale logout 2>/dev/null || true

tailscale up \
    --login-server "$HEADSCALE_URL" \
    --authkey "$AUTHKEY" \
    --hostname "$HOSTNAME" \
    --accept-routes \
    --accept-dns

echo ""
echo -e "${YELLOW}[4/4] Verifying connection...${NC}"
sleep 2

tailscale status

echo ""
echo -e "${GREEN}=== Done! ===${NC}"
echo -e "This machine is now accessible as: ${GREEN}${HOSTNAME}.webfactor.internal${NC}"
echo -e "Tailscale IP: ${GREEN}$(tailscale ip -4)${NC}"
echo ""
echo "Useful commands:"
echo "  tailscale status     - Show connected nodes"
echo "  tailscale ping <host>.webfactor.internal - Ping another node"
echo "  tailscale netcheck   - Check network connectivity"
