#!/usr/bin/env bash
# Repair helper for 188 registry.wooo.work HTTP-01 renewal.
# Default is dry-run. Use --apply on 188 as root after reviewing the plan.
set -euo pipefail

APPLY=0
DOMAIN="${REGISTRY_CERTBOT_DOMAIN:-registry.wooo.work}"
WEBROOT="${REGISTRY_CERTBOT_WEBROOT:-/var/www/certbot}"
NGINX_SNIPPET="${REGISTRY_CERTBOT_NGINX_SNIPPET:-/etc/nginx/conf.d/registry-acme-http.conf}"
CERTBOT_BIN="${REGISTRY_CERTBOT_BIN:-/snap/bin/certbot}"

usage() {
  cat <<'USAGE'
Usage: sudo bash scripts/ops/188-registry-certbot-fix.sh [--apply]

Fixes the known 188 drift where registry.wooo.work HTTP-01 traffic falls through
to the aiops.wooo.work default server and certbot cannot renew the registry cert.

Default mode is dry-run and prints the exact actions. --apply requires root.

Environment:
  REGISTRY_CERTBOT_DOMAIN        Default: registry.wooo.work
  REGISTRY_CERTBOT_WEBROOT       Default: /var/www/certbot
  REGISTRY_CERTBOT_NGINX_SNIPPET Default: /etc/nginx/conf.d/registry-acme-http.conf
  REGISTRY_CERTBOT_BIN           Default: /snap/bin/certbot
USAGE
}

while [ "$#" -gt 0 ]; do
  case "$1" in
    --apply)
      APPLY=1
      ;;
    -h|--help)
      usage
      exit 0
      ;;
    *)
      echo "Unknown argument: $1" >&2
      usage >&2
      exit 64
      ;;
  esac
  shift
done

run() {
  if [ "$APPLY" -eq 1 ]; then
    "$@"
  else
    printf 'DRY-RUN:'
    printf ' %q' "$@"
    printf '\n'
  fi
}

write_snippet() {
  local tmp
  tmp="$(mktemp)"
  cat > "$tmp" <<EOF
# Managed by AWOOOI registry certbot repair.
# LetsEncrypt HTTP-01 must not fall through to aiops.wooo.work.
server {
    listen 80;
    server_name ${DOMAIN};

    location /.well-known/acme-challenge/ {
        root ${WEBROOT};
        default_type "text/plain";
    }

    location / {
        return 301 https://\$host\$request_uri;
    }
}
EOF
  run install -m 0644 "$tmp" "$NGINX_SNIPPET"
  rm -f "$tmp"
}

if [ "$APPLY" -eq 1 ] && [ "$(id -u)" -ne 0 ]; then
  echo "--apply must be run as root on 188" >&2
  exit 77
fi

if [ "$APPLY" -eq 1 ] && [ ! -x "$CERTBOT_BIN" ]; then
  echo "certbot binary not executable: $CERTBOT_BIN" >&2
  exit 69
fi

echo "Plan: repair HTTP-01 route for ${DOMAIN}, renew via ${CERTBOT_BIN}, reload nginx."
run install -d -m 0755 "$WEBROOT"
write_snippet
run nginx -t
run systemctl reload nginx

if [ "$APPLY" -eq 1 ]; then
  code="$(curl -s -o /dev/null -w '%{http_code}' --max-time 8 "http://${DOMAIN}/.well-known/acme-challenge/codex-route-check" || true)"
  if [ "$code" != "404" ]; then
    echo "Unexpected ACME route status after nginx reload: ${code}; expected 404 from ${DOMAIN}, not redirect/default vhost" >&2
    exit 1
  fi
fi

run "$CERTBOT_BIN" renew --cert-name "$DOMAIN" --deploy-hook "systemctl reload nginx"

if [ -x /snap/bin/certbot ]; then
  run systemctl disable --now certbot.timer
  run systemctl reset-failed certbot.service
fi

if [ "$APPLY" -eq 1 ]; then
  openssl x509 -noout -subject -issuer -dates -in "/etc/letsencrypt/live/${DOMAIN}/fullchain.pem"
  systemctl status snap.certbot.renew.timer --no-pager -l | sed -n '1,25p' || true
else
  echo "Dry-run only. Re-run with --apply on 188 as root to execute."
fi
