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

ROOT="${CAMP_DEPLOY_ROOT:-/var/www/camps}"
PUBLIC_ROOT="${CAMP_CATALOG_PUBLIC_ROOT:-/var/www/camp-list}"
SAFE_RE='^[a-z0-9][a-z0-9-]{0,62}$'

fail() {
  echo "camp-admin-root: $*" >&2
  exit 1
}

action="${1:-}"
slug="${2:-}"
host="${3:-}"

[[ "$action" == "ensure-camp" ]] || fail "unsupported action"
[[ "$slug" =~ $SAFE_RE ]] || fail "invalid slug"
[[ "$host" == "${slug}.sg.superbrain-ai.com" ]] || fail "host must match slug.sg.superbrain-ai.com"

mkdir -p "$ROOT/$slug" "$PUBLIC_ROOT"
chown -R campdeploy:www-data "$ROOT/$slug" "$PUBLIC_ROOT" 2>/dev/null || true
chmod 2775 "$ROOT/$slug" "$PUBLIC_ROOT" 2>/dev/null || true

conf="/etc/nginx/sites-available/${slug}"
if [[ -f "$conf" ]] && grep -Eq 'managed by Certbot|ssl_certificate' "$conf"; then
  perl -0pi -e "s#root\\s+/var/www/camps/[^;]+;#root /var/www/camps/${slug};#g; s#try_files\\s+\\\$uri(?:\\s+\\\$uri/)?\\s+=404;#try_files \\\$uri/index.html \\\$uri =404;#g" "$conf"
else
  cat > "$conf" <<EOF
server {
    listen 80;
    server_name ${host};
    root /var/www/camps/${slug};
    index index.html;

    location / {
        try_files \$uri/index.html \$uri =404;
    }

    add_header X-Content-Type-Options nosniff;
    add_header X-Frame-Options SAMEORIGIN;

    gzip on;
    gzip_types text/plain text/css application/json application/javascript text/xml;
}
EOF
fi

ln -sf "$conf" "/etc/nginx/sites-enabled/${slug}"
nginx -t
systemctl reload nginx

if command -v certbot >/dev/null 2>&1 && [[ "${CAMP_ADMIN_SKIP_CERTBOT:-0}" != "1" ]]; then
  certbot --nginx -d "$host" --non-interactive --agree-tos -m admin@superbrain-ai.com
fi

echo "camp ready: https://${host}/"
