#!/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'
BLUE='\033[0;34m'
NC='\033[0m'

echo -e "${BLUE}╔════════════════════════════════════════╗${NC}"
echo -e "${BLUE}║      Dyolink — Production Deploy       ║${NC}"
echo -e "${BLUE}╚════════════════════════════════════════╝${NC}"

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

SECRETS_DIR="${DEPLOY_SECRETS_DIR:-./secrets}"
if [ ! -f "${SECRETS_DIR}/database.env" ] || [ ! -f "${SECRETS_DIR}/backend.env" ]; then
  echo -e "${RED}Missing secrets in ${SECRETS_DIR}/${NC}"
  echo "  Need: database.env and backend.env"
  echo "  Copy from database.prod.env.example and backend.prod.env.example"
  exit 1
fi

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

if ! docker volume inspect dyolink_certbot_conf >/dev/null 2>&1 || \
   ! docker run --rm -v dyolink_certbot_conf:/etc/letsencrypt:ro alpine \
      test -f "/etc/letsencrypt/live/${DOMAIN}/fullchain.pem" 2>/dev/null; then
  echo -e "${YELLOW}No SSL certificate yet — running init-letsencrypt.sh first...${NC}"
  ./scripts/init-letsencrypt.sh
else
  ./scripts/render-nginx-ssl.sh
  echo -e "${YELLOW}Pulling images...${NC}"
  "${COMPOSE[@]}" pull backend frontend
  echo -e "${YELLOW}Starting stack...${NC}"
  "${COMPOSE[@]}" up -d --force-recreate nginx
  "${COMPOSE[@]}" up -d
fi

sleep 8
echo -e "\n${GREEN}=== Status ===${NC}"
"${COMPOSE[@]}" ps

echo -e "\n${BLUE}App URL: https://${DOMAIN}${NC}"
echo -e "${BLUE}API health: https://${DOMAIN}/api/health${NC}"
