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

# ====== KONFIG: HIER FEST EINTRAGEN ======
DOMAIN="n8n.hx-ki.com"
UPSTREAM="127.0.0.1:5678"
HETZNER_DNS_API_TOKEN="PASTE_DNS_TOKEN_HERE"
# =========================================

# --- Vorbedingungen ---
command -v caddy >/dev/null || { echo "ERROR: caddy fehlt"; exit 1; }
systemctl list-unit-files | grep -q '^caddy\.service' || { echo "ERROR: caddy.service fehlt"; exit 1; }

# --- Token in systemd-Service ---
install -d -m 0755 /etc/systemd/system/caddy.service.d
cat >/etc/systemd/system/caddy.service.d/env.conf <<EOF
[Service]
Environment=HETZNER_DNS_API_TOKEN=${HETZNER_DNS_API_TOKEN}
EOF
chmod 0640 /etc/systemd/system/caddy.service.d/env.conf

# --- Caddyfile ---
install -d -m 0755 /etc/caddy
cat >/etc/caddy/Caddyfile <<EOF
${DOMAIN} {
  tls {
    dns hetzner
  }
  reverse_proxy ${UPSTREAM}
}
EOF

# --- Hetzner DNS Plugin sicherstellen ---
if ! caddy list-modules 2>/dev/null | grep -q 'dns.providers.hetzner'; then
  tmp="/tmp/xcaddy.$$"
  rm -rf "$tmp"; mkdir -p "$tmp"; cd "$tmp"
  apt-get update -y >/dev/null
  apt-get install -y curl tar >/dev/null
  curl -fsSL https://github.com/caddyserver/xcaddy/releases/latest/download/xcaddy_linux_amd64.tar.gz | tar xz
  ./xcaddy build --with github.com/caddy-dns/hetzner
  install -m 0755 caddy /usr/bin/caddy
  rm -rf "$tmp"
fi

systemctl daemon-reload
systemctl restart caddy

# --- Beweis ---
systemctl show caddy -p Environment | grep -q HETZNER_DNS_API_TOKEN || { echo "ERROR: Token nicht im Service-Kontext"; exit 2; }

echo "OK: Caddy läuft. Letzte Logs:"
journalctl -u caddy -n 80 --no-pager
