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

repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$repo_root"

if [[ -f .env ]]; then
  set -a
  # shellcheck source=/dev/null
  source .env
  set +a
fi

POOL_DOMAIN="${POOL_DOMAIN:-pool.vexonus.com}"
VEX_DOCS_DOMAIN="${VEX_DOCS_DOMAIN:-docs.vexonus.com}"
VEX_POOL_ROOT="${VEX_POOL_ROOT:-/opt/vexon-pool}"
VEX_LOG_DIR="${VEX_LOG_DIR:-$VEX_POOL_ROOT/log}"

install -d -m 775 "$VEX_LOG_DIR"
log_file="$VEX_LOG_DIR/ssl-renew.log"
touch "$log_file"

log() {
  printf '%s %s\n' "$(date '+%Y-%m-%d %H:%M:%S %Z')" "$*" | tee -a "$log_file"
}

if [[ "$(id -u)" != "0" ]]; then
  log "[FAIL] run as root: sudo bash scripts/ssl-renew-check.sh"
  exit 1
fi

if ! command -v certbot >/dev/null 2>&1; then
  log "[WARN] certbot is not installed; run scripts/install-https.sh after DNS points to this server"
  exit 0
fi

if command -v nginx >/dev/null 2>&1; then
  nginx -t
  systemctl start nginx >/dev/null 2>&1 || true
fi

log "running certbot renew"
certbot renew --quiet --deploy-hook "systemctl reload nginx"

if command -v openssl >/dev/null 2>&1; then
  for domain in "$POOL_DOMAIN" "$VEX_DOCS_DOMAIN"; do
    cert="/etc/letsencrypt/live/${domain}/fullchain.pem"
    if [[ -f "$cert" ]]; then
      end_date="$(openssl x509 -enddate -noout -in "$cert" | cut -d= -f2-)"
      log "[OK] $domain certificate expires: $end_date"
    else
      log "[WARN] certificate not found for $domain at $cert"
    fi
  done
fi

log "[OK] SSL renewal check complete"
