#!/usr/bin/env bash
set -euo pipefail

SCRIPT_NAME=$(basename "$0")

log() {
  echo "[$(date +'%F %T')] $*"
  logger -t "$SCRIPT_NAME" "$*"
}

# ─── Pre-checks ───

[[ $EUID -ne 0 ]] && { log "❌ This script must be run as root"; exit 1; }

command -v tailscale >/dev/null || { log "❌ 'tailscale' command not found"; exit 1; }
command -v jq >/dev/null || { log "❌ 'jq' command not found"; exit 1; }
command -v ip >/dev/null || { log "❌ 'ip' command not found"; exit 1; }

# ─── Singleton Guard ───
if pgrep -f "$SCRIPT_NAME" | grep -vw $$ >/dev/null; then
  log "⚠️ Script already running — exiting"
  exit 0
fi

# ─── Wait for Tailscale to come online ───
log "⏳ Waiting for Tailscale to be online..."
until tailscale status --peers=false --json | jq -e '.Self.Online' >/dev/null 2>&1; do
  sleep 2
done
log "✅ Tailscale is online"

# ─── Retrieve Tailscale IP and Interface ───
TAIL_IP=$(tailscale ip -4 | head -n 1)
TS_DEV=$(ip -o link | awk -F': ' '/tailscale/{print $2; exit}')

if [[ -z "$TAIL_IP" || -z "$TS_DEV" ]]; then
  log "❌ Could not detect Tailscale IP or interface"
  exit 1
fi

# ─── Check Existing Route ───
EXISTING_ROUTE=$(ip route show 192.168.10.0/24 || true)

if [[ "$EXISTING_ROUTE" == "192.168.10.0/24 via $TAIL_IP dev $TS_DEV" ]]; then
  log "✅ Route already in place: $EXISTING_ROUTE"
else
  if [[ -n "$EXISTING_ROUTE" ]]; then
    log "🔁 Updating existing route:"
    log "   Old: $EXISTING_ROUTE"
    log "   New: 192.168.10.0/24 via $TAIL_IP dev $TS_DEV"
  else
    log "➕ Adding new route: 192.168.10.0/24 via $TAIL_IP dev $TS_DEV"
  fi
  ip route replace 192.168.10.0/24 via "$TAIL_IP" dev "$TS_DEV"
  log "✅ Route applied."
fi

# ─── Ensure Local LAN Rule Exists ───
RULE_EXISTS=$(ip rule show | grep -Fq "to 192.168.10.0/24 lookup main" && echo yes || echo no)

if [[ "$RULE_EXISTS" == "yes" ]]; then
  log "✅ ip rule already exists for 192.168.10.0/24 → lookup main"
else
  log "➕ Adding ip rule: to 192.168.10.0/24 priority 2500 lookup main"
  ip rule add to 192.168.10.0/24 priority 2500 lookup main
  log "✅ Rule added."
fi