#!/usr/bin/env bash
# ============================================================================
# deploy.sh - despliega LicenciasMIG en el VPS
# Ejecutar como root en el VPS, despues de subir el proyecto a /tmp/LicenciasMIG
# ============================================================================
set -euo pipefail

PROJ_DIR=/var/www/html/LicenciasMIG
SRC_DIR=${1:-/tmp/LicenciasMIG}
PORT=${PORT:-95}
APACHE_VHOST=/etc/apache2/sites-available/licenciasmig.conf

echo "==> Verificando dependencias del sistema..."
apt-get update -qq
apt-get install -yqq python3 python3-venv python3-pip libapache2-mod-wsgi-py3 unixodbc-dev

echo "==> Sincronizando codigo a $PROJ_DIR ..."
mkdir -p "$PROJ_DIR"
rsync -a --delete \
    --exclude='venv/' --exclude='__pycache__/' --exclude='.git/' --exclude='*.pyc' \
    --exclude='.env' \
    "$SRC_DIR"/ "$PROJ_DIR"/

echo "==> Asegurando .env (copiando .env.example si no existe)..."
if [[ ! -f "$PROJ_DIR/.env" ]]; then
    cp "$PROJ_DIR/.env.example" "$PROJ_DIR/.env"
    echo "  ATENCION: edita $PROJ_DIR/.env con las credenciales reales antes de seguir."
fi

echo "==> Creando virtualenv..."
if [[ ! -d "$PROJ_DIR/venv" ]]; then
    python3 -m venv "$PROJ_DIR/venv"
fi
"$PROJ_DIR/venv/bin/pip" install --quiet --upgrade pip
"$PROJ_DIR/venv/bin/pip" install --quiet -r "$PROJ_DIR/requirements.txt"

echo "==> Permisos..."
chown -R www-data:www-data "$PROJ_DIR"
find "$PROJ_DIR" -type d -exec chmod 755 {} \;
find "$PROJ_DIR" -type f -exec chmod 644 {} \;
chmod 600 "$PROJ_DIR/.env" 2>/dev/null || true

echo "==> Configurando Apache (puerto $PORT)..."
if ! grep -qE "^Listen $PORT\b" /etc/apache2/ports.conf; then
    echo "Listen $PORT" >> /etc/apache2/ports.conf
fi

cp "$PROJ_DIR/deploy/apache_vhost.conf" "$APACHE_VHOST"
sed -i "s/<VirtualHost \*:95>/<VirtualHost *:$PORT>/" "$APACHE_VHOST"

a2enmod wsgi headers > /dev/null 2>&1 || true
a2ensite licenciasmig > /dev/null

echo "==> Abriendo puerto $PORT en UFW..."
ufw allow "$PORT"/tcp > /dev/null || true

echo "==> Validando config Apache..."
apache2ctl configtest

echo "==> Recargando Apache..."
systemctl reload apache2

echo "==> Smoke test..."
sleep 1
if curl -sf "http://127.0.0.1:$PORT/health" | grep -q '"ok": true'; then
    echo "  /health OK"
else
    echo "  /health FALLO - revisa /var/log/apache2/LicenciasMIG_error.log"
    exit 1
fi

echo ""
echo "============================================================================"
echo " LicenciasMIG desplegado en http://194.163.45.32:$PORT"
echo " Endpoint SOAP: http://194.163.45.32:$PORT/LicenciasService.asmx"
echo " WSDL:          http://194.163.45.32:$PORT/LicenciasService.asmx?wsdl"
echo ""
echo " Pasos siguientes:"
echo "  1. Editar $PROJ_DIR/.env con credenciales reales"
echo "  2. Ejecutar SQL: sql/01_create_database.sql, sql/02_create_tables.sql"
echo "  3. Inicializar admin: curl http://127.0.0.1:$PORT/init-db"
echo "  4. (Opcional) Migrar datos viejos: python sql/migrate_from_clientesmig.py"
echo "  5. Login: http://194.163.45.32:$PORT/login (admin/admin123 - cambiar!)"
echo "============================================================================"
