#!/bin/sh
# Clawdie Shell — Tailscale Module
# Purpose: Recommended Tailscale install + enablement for secure remote access
# POSIX-compliant (no bash-isms)

set -eu

# Configuration (can be overridden for testing)
RC_CONF="${RC_CONF:-/etc/rc.conf}"
LOG_FILE="${LOG_FILE:-/var/log/clawdie-firstboot.log}"
PROGRESS_FILE="${PROGRESS_FILE:-/var/log/clawdie-firstboot.progress}"

# Inputs (caller sets these)
# FEATURE_TAILSCALE   - YES/NO (wizard choice, default YES)
# TAILSCALE_AUTHKEY   - optional device auth key (tskey-...)
# ASSISTANT_NAME      - used to derive default hostname if needed
# AGENT_DOMAIN        - optional, used to derive a hostname label if not local-only

# ============================================================================
# MAIN ENTRY POINT
# ============================================================================

clawdie_shell_tailscale_setup() {
  # Tailscale is recommended but optional
  # Skip if disabled by user choice (wizard) or build-time decision (missing auth key)
  if [ "${FEATURE_TAILSCALE:-YES}" != "YES" ]; then
    log_msg "[tailscale] Skipping (FEATURE_TAILSCALE != YES)"
    return 0
  fi

  log_msg "[tailscale] Starting Tailscale setup (recommended for secure access)"

  # Ensure tailscale is installed (offline repo if available)
  if ! command -v tailscale >/dev/null 2>&1; then
    log_msg "[tailscale] Installing tailscale package"
    if ! pkg install -y tailscale >/dev/null 2>&1; then
      log_msg "[tailscale] WARNING: pkg install tailscale failed (continuing)"
      return 0
    fi
  fi

  # Enable tailscaled
  if command -v sysrc >/dev/null 2>&1; then
    sysrc tailscaled_enable=YES >/dev/null 2>&1 || true
  else
    clawdie_shell_tailscale_sysrc "tailscaled_enable=YES"
  fi

  # Start service (may fail in chroot; non-fatal)
  if command -v service >/dev/null 2>&1; then
    service tailscaled onestart >/dev/null 2>&1 || {
      log_msg "[tailscale] tailscaled could not start (expected in chroot)"
    }
  fi

  # Derive hostname (safe default if unset)
  local hostname
  hostname=""
  if [ -n "${AGENT_DOMAIN:-}" ]; then
    case "$AGENT_DOMAIN" in
      home.arpa|*.home.arpa) hostname="" ;;
      *) hostname="${AGENT_DOMAIN%%.*}" ;;
    esac
  fi
  if [ -z "$hostname" ] && [ -n "${ASSISTANT_NAME:-}" ]; then
    hostname=$(echo "$ASSISTANT_NAME" | tr 'A-Z' 'a-z' | sed 's/[^a-z0-9]//g')
  fi
  [ -n "$hostname" ] || hostname="clawdie"

  # Bring up Tailscale (non-fatal if auth not completed)
  local output
  if [ -n "${TAILSCALE_AUTHKEY:-}" ]; then
    output=$(tailscale up --authkey "$TAILSCALE_AUTHKEY" --hostname "$hostname" 2>&1 || true)
  else
    output=$(tailscale up --hostname "$hostname" 2>&1 || true)
  fi

  if [ -n "$output" ]; then
    echo "$output" | while IFS= read -r line; do
      [ -n "$line" ] && log_msg "[tailscale] $line"
    done
  fi

  echo "[TAILSCALE] COMPLETE" >> "$PROGRESS_FILE"
  log_msg "[tailscale] Setup complete"
  return 0
}

# ============================================================================
# RC.CONF HELPER
# ============================================================================

clawdie_shell_tailscale_sysrc() {
  local var_assignment="$1"
  local var_name

  var_name=$(echo "$var_assignment" | cut -d= -f1)

  if [ ! -f "$RC_CONF" ]; then
    touch "$RC_CONF"
  fi

  if grep -q "^${var_name}=" "$RC_CONF" 2>/dev/null; then
    sed -i '' "s|^${var_name}=.*|${var_assignment}|" "$RC_CONF"
  else
    echo "$var_assignment" >> "$RC_CONF"
  fi
}

# ============================================================================
# LOGGING HELPER
# ============================================================================

log_msg() {
  echo "$(date '+%H:%M:%S') $1" | tee -a "$LOG_FILE" 2>/dev/null || true
}

# Only run if sourced directly (not during test)
if [ "${SHELL_TAILSCALE_TEST:-0}" -eq 0 ]; then
  clawdie_shell_tailscale_setup
fi
