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

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

GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m'

if [ ! -f .env ]; then
  echo -e "${RED}Missing .env — copy deploy.prod.env.example to .env${NC}"
  exit 1
fi

set -a
# shellcheck disable=SC1091
source .env
set +a

: "${DOMAIN:?Set DOMAIN in .env}"
: "${LETSENCRYPT_EMAIL:?Set LETSENCRYPT_EMAIL in .env}"

COMPOSE=(docker compose -f docker-compose.prod.yml --env-file .env)

mkdir -p nginx/generated logs/nginx database/backups

CERT_PATH="certbot_conf/live/${DOMAIN}/fullchain.pem"
if docker volume inspect dyolink_certbot_conf >/dev/null 2>&1; then
  if docker run --rm -v dyolink_certbot_conf:/etc/letsencrypt:ro alpine \
    test -f "/etc/letsencrypt/live/${DOMAIN}/fullchain.pem"; then
    echo -e "${GREEN}Certificate already exists for ${DOMAIN}${NC}"
    ./scripts/render-nginx-ssl.sh
    "${COMPOSE[@]}" up -d --force-recreate nginx
    "${COMPOSE[@]}" up -d
    exit 0
  fi
fi

echo -e "${YELLOW}Phase 1: bootstrap nginx (HTTP) for ACME challenge...${NC}"
cp nginx/nginx.bootstrap.conf nginx/generated/default.conf
"${COMPOSE[@]}" up -d nginx

echo -e "${YELLOW}Phase 2: request Let's Encrypt certificate...${NC}"
CERTBOT_ARGS=(
  certonly
  --webroot
  -w /var/www/certbot
  --email "$LETSENCRYPT_EMAIL"
  --agree-tos
  --no-eff-email
  -d "$DOMAIN"
)

if [ -n "${CERTBOT_EXTRA_DOMAINS:-}" ]; then
  for extra in $CERTBOT_EXTRA_DOMAINS; do
    CERTBOT_ARGS+=(-d "$extra")
  done
fi

if [ "${LETSENCRYPT_STAGING:-0}" = "1" ]; then
  CERTBOT_ARGS+=(--staging)
  echo -e "${YELLOW}Using Let's Encrypt staging (test) certificates${NC}"
fi

"${COMPOSE[@]}" run --rm --entrypoint certbot certbot "${CERTBOT_ARGS[@]}"

echo -e "${YELLOW}Phase 3: enable HTTPS nginx config...${NC}"
./scripts/render-nginx-ssl.sh
"${COMPOSE[@]}" up -d --force-recreate nginx
"${COMPOSE[@]}" up -d

echo -e "${GREEN}SSL ready for https://${DOMAIN}${NC}"
echo -e "${GREEN}Certbot renewal container is running (checks every 12h).${NC}"
