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

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
HOST="${SCOPEWRIT_VPS_HOST:-vps2}"
DOMAIN="${SCOPEWRIT_DOMAIN:-scopewrit.cyberelf.link}"
BOOTSTRAP_CONFIG="$ROOT/deploy/scopewrit.bootstrap.nginx"
FINAL_CONFIG="$ROOT/deploy/scopewrit.nginx"
STAMP="$(date -u +%Y%m%dT%H%M%SZ)"
REMOTE_BOOTSTRAP="/tmp/scopewrit-${STAMP}.bootstrap.nginx"
REMOTE_FINAL="/tmp/scopewrit-${STAMP}.final.nginx"

for required in "$BOOTSTRAP_CONFIG" "$FINAL_CONFIG"; do
  [[ -f "$required" ]] || {
    echo "missing Nginx config: $required" >&2
    exit 1
  }
done

scp "$BOOTSTRAP_CONFIG" "$HOST:$REMOTE_BOOTSTRAP"
scp "$FINAL_CONFIG" "$HOST:$REMOTE_FINAL"

ssh "$HOST" sudo bash -s -- \
  "$DOMAIN" \
  "$STAMP" \
  "$REMOTE_BOOTSTRAP" \
  "$REMOTE_FINAL" <<'REMOTE'
set -euo pipefail

domain="$1"
stamp="$2"
bootstrap="$3"
final="$4"
available="/etc/nginx/sites-available/$domain"
enabled="/etc/nginx/sites-enabled/$domain"
backup_dir="/var/backups/scopewrit"
backup="$backup_dir/$stamp.nginx"
had_previous=0

mkdir -p "$backup_dir"
if test -f "$available"; then
  cp "$available" "$backup"
  had_previous=1
fi

cleanup() {
  rm -f -- "$bootstrap" "$final"
}
trap cleanup EXIT

rollback() {
  echo "rolling back ScopeWrit Nginx config" >&2
  if [[ "$had_previous" -eq 1 ]]; then
    cp "$backup" "$available"
    ln -sfn "$available" "$enabled"
  else
    rm -f -- "$enabled" "$available"
  fi
  nginx -t
  systemctl reload nginx
}

install -o root -g root -m 0644 "$bootstrap" "$available"
ln -sfn "$available" "$enabled"
if ! nginx -t || ! systemctl reload nginx; then
  rollback
  exit 1
fi

if ! certbot certonly \
  --webroot \
  --webroot-path /var/www/html \
  --cert-name "$domain" \
  --domains "$domain" \
  --non-interactive \
  --agree-tos \
  --keep-until-expiring
then
  rollback
  exit 1
fi

cert="/etc/letsencrypt/live/$domain/fullchain.pem"
key="/etc/letsencrypt/live/$domain/privkey.pem"
if ! test -s "$cert" || ! test -s "$key"; then
  rollback
  exit 1
fi
if ! openssl x509 -in "$cert" -noout -checkend 2592000; then
  rollback
  exit 1
fi
if ! openssl x509 -in "$cert" -noout -ext subjectAltName |
  grep -Fq "DNS:$domain"
then
  rollback
  exit 1
fi

install -o root -g root -m 0644 "$final" "$available"
if ! nginx -t || ! systemctl reload nginx; then
  rollback
  exit 1
fi

healthy=0
for _attempt in $(seq 1 15); do
  response="$(
    curl -fsS \
      --resolve "$domain:443:127.0.0.1" \
      "https://$domain/" 2>/dev/null ||
      true
  )"
  if grep -Fq '<title>ScopeWrit' <<<"$response" &&
    grep -Fqi 'reachable is not authorized' <<<"$response"
  then
    healthy=1
    break
  fi
  sleep 1
done
if [[ "$healthy" -ne 1 ]]; then
  rollback
  exit 1
fi

openssl x509 -in "$cert" -noout -subject -issuer -dates
echo "ScopeWrit ready: https://$domain/"
REMOTE
