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

cd "$(dirname "$0")/.."

if [[ ! -f .env ]]; then
  echo "Missing .env. Copy .env.example to .env and edit it first." >&2
  exit 1
fi

set -a
source .env
set +a

POOL_DOMAIN="${POOL_DOMAIN:-}"
VEX_DOCS_DOMAIN="${VEX_DOCS_DOMAIN:-docs.vexonus.com}"
POOL_ADMIN_EMAIL="${POOL_ADMIN_EMAIL:-}"

if [[ "$(id -u)" != "0" ]]; then
  echo "Run as root: sudo bash scripts/install-https.sh" >&2
  exit 1
fi

if [[ -z "$POOL_DOMAIN" || -z "$VEX_DOCS_DOMAIN" || -z "$POOL_ADMIN_EMAIL" ]]; then
  echo "POOL_DOMAIN, VEX_DOCS_DOMAIN, and POOL_ADMIN_EMAIL must be set in .env" >&2
  exit 1
fi

if ! command -v nginx >/dev/null 2>&1; then
  echo "nginx is required before HTTPS can be enabled." >&2
  exit 1
fi

nginx -t
systemctl start nginx

if grep -Rqs "ppa.launchpad.net/certbot/certbot" /etc/apt/sources.list /etc/apt/sources.list.d; then
  grep -Rl "ppa.launchpad.net/certbot/certbot" /etc/apt/sources.list /etc/apt/sources.list.d \
    | while read -r source_file; do
      mv "$source_file" "${source_file}.disabled"
      echo "Disabled obsolete certbot PPA: $source_file"
    done
fi

apt-get update
DEBIAN_FRONTEND=noninteractive apt-get install -y certbot python3-certbot-nginx

certbot --nginx \
  --non-interactive \
  --agree-tos \
  --redirect \
  --expand \
  --email "$POOL_ADMIN_EMAIL" \
  -d "$POOL_DOMAIN" \
  -d "$VEX_DOCS_DOMAIN"

systemctl reload nginx
certbot renew --dry-run

echo "HTTPS is enabled for $POOL_DOMAIN and $VEX_DOCS_DOMAIN"
