#!/bin/bash
set -euo pipefail

# 🔐 Ensure running as root
if [[ "$EUID" -ne 0 ]]; then
  echo "❌ Please run as root (use sudo)."
  exit 1
fi

ADAPTED_JSON="/etc/caddy/caddy.adapted.json"
FINAL_JSON="/etc/caddy/caddy.final.json"
LOG_DIR="/var/log/caddy"

is_debug_active() {
  systemctl is-active --quiet caddy-debug
}

prepare_environment() {
  echo "🧰 Preparing environment..."
  mkdir -p "$LOG_DIR"
  chown caddy:caddy "$LOG_DIR"

  if [[ ! -f /etc/systemd/system/caddy-debug.service ]]; then
    echo "🛠️ Creating caddy-debug.service..."
    cat <<EOF > /etc/systemd/system/caddy-debug.service
[Unit]
Description=Caddy Web Server (with reverse_proxy debug)
After=network-online.target
Wants=network-online.target
Documentation=https://caddyserver.com/docs/

[Service]
User=caddy
Group=caddy
ExecStart=/usr/bin/caddy run --config /etc/caddy/caddy.final.json
ExecReload=/usr/bin/caddy reload --config /etc/caddy/caddy.final.json
TimeoutStopSec=5s
LimitNOFILE=1048576
LimitNPROC=512
PrivateTmp=true
ProtectSystem=full
AmbientCapabilities=CAP_NET_BIND_SERVICE
CapabilityBoundingSet=CAP_NET_BIND_SERVICE

[Install]
WantedBy=multi-user.target
EOF

    systemctl daemon-reload
  fi
}

enable_debug() {
  echo "📦 Adapting Caddyfile to JSON..."
  caddy adapt --config /etc/caddy/Caddyfile --pretty > "$ADAPTED_JSON"

  echo "🔧 Injecting reverse_proxy DEBUG log config..."
  jq '.logging.logs["reverse_proxy"] = {
    level: "DEBUG",
    include: ["http.handlers.reverse_proxy"],
    writer: {
      output: "file",
      filename: "/var/log/caddy/reverse_proxy.log"
    }
  }' "$ADAPTED_JSON" > "$FINAL_JSON"

  echo "🔁 Stopping caddy.service..."
  systemctl stop caddy || true

  echo "🚀 Starting caddy-debug.service..."
  systemctl start caddy-debug

  echo "✅ Debug mode ENABLED (reverse_proxy logs active)."
}

disable_debug() {
  echo "🔁 Stopping caddy-debug.service..."
  systemctl stop caddy-debug || true

  echo "🚀 Starting standard caddy.service..."
  systemctl start caddy

  echo "✅ Debug mode DISABLED. Running standard Caddyfile."
}

show_status() {
  echo "🔍 Caddy Debug Mode Status:"
  if is_debug_active; then
    echo "🟢 DEBUG mode is currently ACTIVE"
    systemctl status caddy-debug --no-pager
  else
    echo "⚪ DEBUG mode is currently INACTIVE"
    systemctl status caddy --no-pager
  fi
}

# 🧼 Main
prepare_environment

case "${1:-}" in
  --status|-s)
    show_status
    ;;
  --on|--enable)
    echo "🔁 Forcing DEBUG mode ON..."
    enable_debug
    ;;
  --off|--disable)
    echo "🔁 Forcing DEBUG mode OFF..."
    disable_debug
    ;;
  *)
    if is_debug_active; then
      echo "🟢 Debug mode is active — switching OFF..."
      disable_debug
    else
      echo "⚪ Debug mode is inactive — switching ON..."
      enable_debug
    fi
    ;;
esac