#!/bin/bash
set -e

# ───── Configuration ─────
MARKER_DIR="/etc/setup-markers"
MARKER="$MARKER_DIR/caddy_installed"
SHARED_DIR="/myshares/shared"
MY_CADDYFILE="/etc/caddy/Caddyfile"
MY_CADDYSERVICE="/etc/systemd/system/caddy.service"

# ───── Arguments ─────
FORCE=false
for arg in "$@"; do
  case "$arg" in
    --force)
      FORCE=true
      echo "⚠️  Force mode enabled — setup will re-run even if marker exists."
      ;;
    --help|-h)
      echo "Usage: $0 [--force]"
      echo "  --force   Re-run setup even if already marked as completed"
      exit 0
      ;;
    *)
      echo "❌ Unknown option: $arg"
      echo "Run with --help for usage."
      exit 1
      ;;
  esac
done

# ───── Imports ─────
source /opt/scripts_remote/shared_functions.sh

# ───── Skip if already configured ─────
if [ -f "$MARKER" ] && [ "$FORCE" != true ]; then
  echo "✅ Caddy already installed — skipping setup."
  echo "👉 Use --force to re-run setup."
  exit 0
fi

echo "🚀 Installing Caddy..."

# ───── Installation ─────
if ! _isServiceRunning caddy && ! [ -f "$MY_CADDYSERVICE" ]; then
  download_template "$SHARED_DIR/usr/bin/caddy" /usr/bin/
  sudo mkdir -p /var/log/caddy /var/www/html /etc/caddy
  sudo chmod +x /usr/bin/caddy
  sudo groupadd --system caddy >/dev/null 2>&1 || true
  sudo useradd --system \
    --gid caddy \
    --create-home \
    --home-dir /var/lib/caddy \
    --shell /usr/sbin/nologin \
    --comment "Caddy web server" \
    caddy >/dev/null 2>&1 || true
  sudo chown caddy:caddy -R /etc/caddy /var/log/caddy
  sudo rm -f "$MY_CADDYFILE" "$MY_CADDYSERVICE"

  download_template "$SHARED_DIR$MY_CADDYFILE" "$MY_CADDYFILE"
  download_template "$SHARED_DIR$MY_CADDYSERVICE" "$MY_CADDYSERVICE"

  search_and_replace MY_HOSTNAME "$HOSTNAME" "$MY_CADDYFILE"

  sudo chown caddy:sysadmin "$MY_CADDYFILE"
  sudo chmod 600 "$MY_CADDYFILE"
  sudo chmod 644 "$MY_CADDYSERVICE"

  sudo systemctl daemon-reload
  sudo systemctl enable --now caddy

  echo "✅ Finished Installing Caddy"
fi

# ───── Mark as Installed ─────
sudo mkdir -p "$MARKER_DIR"
sudo touch "$MARKER"
echo "📌 Marker created at $MARKER"