#!/bin/bash
# Hawthorn Remote Support Setup (macOS)
# Run: curl -fsSL https://hawthornconsulting.net/setup.sh | bash
# Installs RustDesk (pre-configured) + Tailscale (SSH access) + Enables Remote Login

set -e

# --- Configuration ---
RUSTDESK_SERVER="vpn.gorackup.com"
RUSTDESK_KEY="d3Qo6vL4ZMAnQewtDNXPMEugV2F9sQ5+WQNtARMHYeA="
TEMP_DIR="/tmp/hawthorn-setup"
TS_AUTHKEY="${TS_AUTHKEY:-}"

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

echo ""
echo -e "${CYAN}========================================"
echo "  Hawthorn Remote Support Setup (macOS)"
echo -e "========================================${NC}"
echo ""

# Check for macOS
if [[ "$(uname)" != "Darwin" ]]; then
    echo -e "${RED}[!] This script is for macOS only. Use setup.ps1 for Windows.${NC}"
    exit 1
fi

# Check for sudo (will prompt for password)
echo -e "${YELLOW}This script needs admin privileges. You may be prompted for your password.${NC}"
echo ""
sudo -v || { echo -e "${RED}[!] Admin privileges required.${NC}"; exit 1; }

# Keep sudo alive
while true; do sudo -n true; sleep 60; kill -0 "$$" || exit; done 2>/dev/null &

mkdir -p "$TEMP_DIR"

# ============================================
# STEP 1: Install RustDesk
# ============================================
echo -e "${GREEN}[1/5] Installing RustDesk...${NC}"

if [ -d "/Applications/RustDesk.app" ]; then
    echo "      RustDesk already installed, skipping download."
else
    # Get latest version from GitHub
    echo "      Checking for latest RustDesk version..."
    RUSTDESK_VERSION=$(curl -fsSL https://api.github.com/repos/rustdesk/rustdesk/releases/latest | grep '"tag_name"' | sed 's/.*"tag_name": "//;s/".*//')
    echo "      Latest version: ${RUSTDESK_VERSION}"

    ARCH=$(uname -m)
    if [ "$ARCH" = "arm64" ]; then
        RUSTDESK_URL="https://github.com/rustdesk/rustdesk/releases/download/${RUSTDESK_VERSION}/rustdesk-${RUSTDESK_VERSION}-aarch64.dmg"
    else
        RUSTDESK_URL="https://github.com/rustdesk/rustdesk/releases/download/${RUSTDESK_VERSION}/rustdesk-${RUSTDESK_VERSION}.dmg"
    fi

    echo "      Downloading RustDesk ${RUSTDESK_VERSION}..."
    curl -fsSL "$RUSTDESK_URL" -o "$TEMP_DIR/rustdesk.dmg"

    echo "      Mounting and installing..."
    hdiutil attach "$TEMP_DIR/rustdesk.dmg" -nobrowse -quiet -mountpoint "$TEMP_DIR/rustdesk-mount"
    sudo cp -R "$TEMP_DIR/rustdesk-mount/RustDesk.app" /Applications/
    hdiutil detach "$TEMP_DIR/rustdesk-mount" -quiet
    echo "      RustDesk installed to /Applications."
fi

# ============================================
# STEP 2: Configure RustDesk
# ============================================
echo -e "${GREEN}[2/5] Configuring RustDesk...${NC}"

CONFIG_DIR="$HOME/Library/Preferences/RustDesk"
mkdir -p "$CONFIG_DIR"

cat > "$CONFIG_DIR/RustDesk2.toml" << EOF
rendezvous_server = '$RUSTDESK_SERVER'
nat_type = 1
serial = 0

[options]
custom-rendezvous-server = '$RUSTDESK_SERVER'
key = '$RUSTDESK_KEY'
EOF

echo "      Server configured: $RUSTDESK_SERVER"

# Restart RustDesk if running
killall RustDesk 2>/dev/null || true
sleep 1
open -a RustDesk 2>/dev/null || true
sleep 3

# Get RustDesk ID
RUSTDESK_ID=""
if [ -f "$CONFIG_DIR/RustDesk.toml" ]; then
    RUSTDESK_ID=$(grep "^id = " "$CONFIG_DIR/RustDesk.toml" 2>/dev/null | sed "s/id = '//;s/'//")
fi

# ============================================
# STEP 3: Enable Remote Login (SSH)
# ============================================
echo -e "${GREEN}[3/5] Enabling Remote Login (SSH)...${NC}"

SSH_STATUS=$(sudo systemsetup -getremotelogin 2>/dev/null | grep -i "on" || true)
if [ -n "$SSH_STATUS" ]; then
    echo "      Remote Login already enabled."
else
    sudo systemsetup -setremotelogin on -f 2>/dev/null
    echo "      Remote Login (SSH) enabled."
fi

# macOS firewall — allow SSH if firewall is on
FW_STATUS=$(sudo /usr/libexec/ApplicationFirewall/socketfilterfw --getglobalstate 2>/dev/null | grep -i "enabled" || true)
if [ -n "$FW_STATUS" ]; then
    sudo /usr/libexec/ApplicationFirewall/socketfilterfw --add /usr/sbin/sshd 2>/dev/null || true
    sudo /usr/libexec/ApplicationFirewall/socketfilterfw --unblockapp /usr/sbin/sshd 2>/dev/null || true
    echo "      Firewall rule added for SSH."
else
    echo "      macOS firewall is off — SSH accessible by default."
fi

# ============================================
# STEP 4: Install Tailscale
# ============================================
echo -e "${GREEN}[4/5] Installing Tailscale...${NC}"

if command -v tailscale &>/dev/null || [ -d "/Applications/Tailscale.app" ]; then
    echo "      Tailscale already installed, skipping download."
else
    # Try Homebrew first (fastest), fall back to Mac App Store prompt
    if command -v brew &>/dev/null; then
        echo "      Installing via Homebrew..."
        brew install --cask tailscale 2>/dev/null || true
    else
        echo "      Downloading Tailscale from pkgs.tailscale.com..."
        curl -fsSL "https://pkgs.tailscale.com/stable/Tailscale-latest-macos.zip" -o "$TEMP_DIR/tailscale.zip"
        unzip -qo "$TEMP_DIR/tailscale.zip" -d "$TEMP_DIR/tailscale-extract"
        sudo cp -R "$TEMP_DIR/tailscale-extract/Tailscale.app" /Applications/
        echo "      Tailscale installed to /Applications."
    fi
fi

# ============================================
# STEP 5: Connect Tailscale
# ============================================
echo -e "${GREEN}[5/5] Connecting Tailscale...${NC}"

# Find tailscale CLI
TAILSCALE_CLI=""
if command -v tailscale &>/dev/null; then
    TAILSCALE_CLI="tailscale"
elif [ -f "/Applications/Tailscale.app/Contents/MacOS/Tailscale" ]; then
    # Open the app first so the system extension loads
    open -a Tailscale 2>/dev/null || true
    sleep 3
    TAILSCALE_CLI="/Applications/Tailscale.app/Contents/MacOS/Tailscale"
fi

if [ -n "$TAILSCALE_CLI" ] && [ -n "$TS_AUTHKEY" ]; then
    echo "      Joining Hawthorn network with SSH enabled..."
    sudo $TAILSCALE_CLI up --authkey="$TS_AUTHKEY" --ssh 2>/dev/null || true
    sleep 3
    TS_IP=$($TAILSCALE_CLI ip -4 2>/dev/null || echo "pending")
    echo -e "      ${GREEN}Connected! Tailscale IP: $TS_IP${NC}"
elif [ -n "$TAILSCALE_CLI" ]; then
    echo -e "      ${YELLOW}No auth key provided. Tailscale installed but not connected.${NC}"
    echo "      Hawthorn will send you a connection link separately."
else
    echo -e "      ${YELLOW}Tailscale installed. Open Tailscale.app to get started.${NC}"
    echo "      Hawthorn will send you a connection link separately."
fi

# ============================================
# DONE - Show summary
# ============================================
echo ""
echo -e "${GREEN}========================================"
echo "  Setup Complete!"
echo -e "========================================${NC}"
echo ""

if [ -n "$RUSTDESK_ID" ]; then
    echo -e "  ${CYAN}Your RustDesk ID: $RUSTDESK_ID${NC}"
    echo ""
    echo "  Please send this ID to Hawthorn Consulting"
    echo "  Email: support@hawthornconsulting.net"
    echo "  Phone: (918) 922-0417"
else
    echo "  RustDesk is installed. Open it to find your ID."
    echo "  Send your ID to Hawthorn Consulting."
fi

echo ""
echo "  What was set up:"
echo "    [x] RustDesk (remote desktop support)"
echo "    [x] Remote Login / SSH (enabled)"
echo "    [x] Tailscale (secure network access)"
echo ""

# Cleanup
rm -rf "$TEMP_DIR"

echo "Done! You can close this terminal window."
