#!/usr/bin/env bash
set -e

CADDY_DIR="/etc/caddy"
CADDY_FILE="$CADDY_DIR/Caddyfile"

echo "==> Ensuring Caddy directory exists..."
mkdir -p "$CADDY_DIR"

echo "==> Writing Caddyfile..."
cat > "$CADDY_FILE" <<'EOF'
(common_proxy) {
    reverse_proxy https://10.0.0.11:4443 {
        transport http {
            tls_insecure_skip_verify
        }
        header_up X-Forwarded-Proto https
    }
}

*.elva.my.id, pacs, pacs.local, localhost, 127.0.0.1, 0.0.0.0, 10.0.0.11 {
    tls internal
    import common_proxy
}
EOF

echo "==> Checking if Caddy is installed..."
if ! command -v caddy >/dev/null 2>&1; then
    echo "Caddy not found. Installing..."

    apt update
    apt install -y debian-keyring debian-archive-keyring apt-transport-https curl

    curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/gpg.key' \
        | gpg --dearmor -o /usr/share/keyrings/caddy-stable-archive-keyring.gpg

    curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/debian.deb.txt' \
        | tee /etc/apt/sources.list.d/caddy-stable.list

    chmod o+r /usr/share/keyrings/caddy-stable-archive-keyring.gpg
    chmod o+r /etc/apt/sources.list.d/caddy-stable.list

    apt update
    apt install -y caddy
fi

echo "==> Reloading Caddy..."
if ! systemctl reload caddy; then
    echo "Reload failed. Trying restart..."
    systemctl restart caddy
fi

echo "==> Caddy setup completed successfully."
