#!/usr/bin/env bash
# issue-and-install.sh — sign + install a Let's Encrypt cert via acme.sh
#
# Usage: ./scripts/issue-and-install.sh <host>
#
# Assumes:
#   - nginx vhost already in /etc/nginx/conf.d/<host>.conf (template in templates/)
#   - placeholder self-signed cert already at /etc/nginx/ssl/<host>.{crt,key}
#   - nginx -t is clean
#   - acme.sh is installed at /usr/local/bin/acme.sh (default)
#
# Idempotent: re-running with --force overwrites. Safe to retry on transient failures.
#
set -euo pipefail

if [ "$#" -lt 1 ]; then
  echo "Usage: $0 <hostname> [--reload-cmd <cmd>]" >&2
  echo "Example: $0 api.spannerjun.top" >&2
  exit 1
fi

HOST="$1"
shift || true

RELOAD_CMD="systemctl reload nginx"
while [ "$#" -gt 0 ]; do
  case "$1" in
    --reload-cmd) RELOAD_CMD="$2"; shift 2 ;;
    *) echo "Unknown arg: $1" >&2; exit 1 ;;
  esac
done

ACME=/usr/local/bin/acme.sh
if [ ! -x "$ACME" ]; then
  echo "acme.sh not at $ACME — adjust ACME path in this script" >&2
  exit 1
fi

# Step 1: ensure LE is the default CA (one-time global, idempotent)
echo "[1/4] Ensuring default CA = Let's Encrypt"
"$ACME" --set-default-ca --server letsencrypt >/dev/null 2>&1 || true

# Step 2: issue the cert (webroot mode — challenge path served by nginx vhost)
echo "[2/4] Issuing cert for $HOST (webroot=/var/www/acme-challenge)"
"$ACME" --issue --force -d "$HOST" -w /var/www/acme-challenge

# Step 3: install — copy certs to /etc/nginx/ssl/ and register reload hook
echo "[3/4] Installing cert to /etc/nginx/ssl/ + reload hook"
"$ACME" --install-cert -d "$HOST" --ecc \
  --cert-file       /etc/nginx/ssl/"$HOST".crt \
  --key-file        /etc/nginx/ssl/"$HOST".key \
  --fullchain-file  /etc/nginx/ssl/"$HOST".fullchain.crt \
  --reloadcmd       "$RELOAD_CMD"

# Step 4: verify
echo "[4/4] Verifying"
if ! command -v nginx >/dev/null; then
  echo "nginx not in PATH — skipping reload, run manually" >&2
else
  nginx -t && "$RELOAD_CMD"
fi
openssl x509 -in /etc/nginx/ssl/"$HOST".crt -noout -issuer -dates

echo "OK. cert: /etc/nginx/ssl/$HOST.crt"
echo "    auto-renew: ~/.acme.sh/${HOST}_ecc/${HOST}.conf has ReloadCmd=$RELOAD_CMD"
