#!/usr/bin/env bash
# Enterprise Mail — deploy script.
#
# Validates environment, installs dependencies, builds frontend + backend,
# runs database migrations, and (re)starts only this app's own systemd
# units. Never touches Postgres/Postfix/Dovecot/Apache service state beyond
# `apache2ctl configtest` (read-only validation) — restarting/reloading
# those is left to you, since this app is a tenant of shared infrastructure.
#
# Usage: sudo ./scripts/deploy.sh

set -euo pipefail

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
BACKEND_DIR="$ROOT_DIR/backend"
FRONTEND_DIR="$ROOT_DIR/frontend"

log()  { printf '\033[1;34m[deploy]\033[0m %s\n' "$1"; }
die()  { printf '\033[1;31m[deploy][error]\033[0m %s\n' "$1" >&2; exit 1; }

# --- 1. Validate environment --------------------------------------------------
[[ -f "$BACKEND_DIR/.env" ]] || die "$BACKEND_DIR/.env is missing. Copy backend/.env.example and fill it in first."
[[ -f "$FRONTEND_DIR/.env" ]] || die "$FRONTEND_DIR/.env is missing. Copy frontend/.env.example and fill it in first."

log "Checking required backend env vars..."
required_vars=(DATABASE_URL SESSION_SECRET IMAP_HOST SMTP_HOST APP_URL)
missing=0
for var in "${required_vars[@]}"; do
  if ! grep -qE "^${var}=.+" "$BACKEND_DIR/.env"; then
    printf '  missing or empty: %s\n' "$var"
    missing=1
  fi
done
[[ "$missing" == "0" ]] || die "Fix backend/.env before deploying."

# --- 2. Install dependencies --------------------------------------------------
log "Installing backend dependencies..."
(cd "$BACKEND_DIR" && npm ci)

log "Installing frontend dependencies..."
(cd "$FRONTEND_DIR" && npm ci)

# --- 3. Build ------------------------------------------------------------------
log "Building backend (TypeScript -> dist/)..."
(cd "$BACKEND_DIR" && npm run build)

log "Building frontend (vite build)..."
(cd "$FRONTEND_DIR" && npm run build)

# --- 4. Migrate ------------------------------------------------------------------
log "Running database migrations..."
(cd "$BACKEND_DIR" && npm run migrate)

# --- 5. Validate configuration -------------------------------------------------
if command -v apache2ctl >/dev/null 2>&1; then
  log "Validating Apache configuration (apache2ctl configtest)..."
  apache2ctl configtest || die "Apache configtest failed — fix before reloading."
fi
if command -v postfix >/dev/null 2>&1; then
  log "Validating Postfix configuration (postfix check)..."
  postfix check || die "postfix check failed."
fi
if command -v doveconf >/dev/null 2>&1; then
  log "Validating Dovecot configuration (doveconf -n)..."
  doveconf -n >/dev/null || die "doveconf failed to parse configuration."
fi

# --- 6. Restart only this app's services ---------------------------------------
log "Restarting enterprise-mail-backend and enterprise-mail-frontend..."
systemctl daemon-reload
systemctl restart enterprise-mail-backend
systemctl restart enterprise-mail-frontend

if command -v apache2ctl >/dev/null 2>&1; then
  log "Reloading Apache2 (reload, not restart — avoids dropping other sites' connections)..."
  systemctl reload apache2
fi

# --- 7. Health check -------------------------------------------------------------
log "Running health check..."
sleep 2
"$ROOT_DIR/scripts/health-check.sh" || die "Post-deploy health check failed — check journalctl -u enterprise-mail-backend"

log "Deploy complete."
