#!/bin/bash
# =============================================================================
# Script de despliegue - Registro de Equipos Online
# Sistema operativo: CentOS 7.9
# Ejecutar como root: bash install-centos7.sh
# =============================================================================

set -e

APP_NAME="registrodeequipos"
APP_DIR="/var/www/${APP_NAME}"
LOG_DIR="/var/log/${APP_NAME}"
NGINX_CONF="/etc/nginx/conf.d/${APP_NAME}.conf"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_DIR="$(cd "${SCRIPT_DIR}/.." && pwd)"

echo "============================================"
echo " Despliegue: ${APP_NAME}"
echo "============================================"

# --- Variables configurables ---
read -rp "Dominio o IP del servidor (ej: midominio.com o 192.168.1.10): " SERVER_NAME
read -rp "Nombre de la base de datos [registro_equipos]: " DB_NAME
DB_NAME=${DB_NAME:-registro_equipos}
read -rp "Usuario MySQL de la aplicación [registro_user]: " DB_USER
DB_USER=${DB_USER:-registro_user}
read -rsp "Contraseña MySQL de la aplicación: " DB_PASS
echo
read -rsp "Contraseña root de MySQL/MariaDB: " MYSQL_ROOT_PASS
echo
read -rp "Puerto interno de Node.js [3000]: " APP_PORT
APP_PORT=${APP_PORT:-3000}

echo ""
echo "[1/10] Instalando dependencias del sistema..."
yum install -y epel-release
yum install -y git curl rsync nginx mariadb-server firewalld

echo "[2/10] Instalando Node.js 18 LTS..."
if ! command -v node &>/dev/null || [[ $(node -v | cut -d. -f1 | tr -d v) -lt 18 ]]; then
  curl -fsSL https://rpm.nodesource.com/setup_18.x | bash -
  yum install -y nodejs
fi
node -v
npm -v

echo "[3/10] Instalando PM2..."
npm install -g pm2

echo "[4/10] Iniciando MariaDB..."
systemctl enable mariadb
systemctl start mariadb

echo "[5/10] Creando base de datos y usuario..."
mysql -u root -p"${MYSQL_ROOT_PASS}" <<EOF
CREATE DATABASE IF NOT EXISTS \`${DB_NAME}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
GRANT ALL PRIVILEGES ON \`${DB_NAME}\`.* TO '${DB_USER}'@'localhost' IDENTIFIED BY '${DB_PASS}';
FLUSH PRIVILEGES;
EOF

echo "[6/10] Copiando proyecto a ${APP_DIR}..."
mkdir -p "${APP_DIR}"
rsync -a --exclude node_modules --exclude .env "${PROJECT_DIR}/" "${APP_DIR}/"

echo "[7/10] Configurando variables de entorno..."
cat > "${APP_DIR}/.env" <<EOF
PORT=${APP_PORT}
DB_HOST=127.0.0.1
DB_PORT=3306
DB_USER=${DB_USER}
DB_PASSWORD=${DB_PASS}
DB_NAME=${DB_NAME}
DNI_API_URL=https://api.facturandala.com/api/ConsultaDni
EOF
chmod 600 "${APP_DIR}/.env"

echo "[8/10] Instalando dependencias npm y aplicando schema..."
cd "${APP_DIR}"
npm install --production

mysql -u "${DB_USER}" -p"${DB_PASS}" "${DB_NAME}" < "${APP_DIR}/database/schema.sql"

echo "[9/10] Configurando PM2..."
mkdir -p "${LOG_DIR}"
pm2 delete "${APP_NAME}" 2>/dev/null || true
pm2 start "${APP_DIR}/ecosystem.config.js"
pm2 save
pm2 startup systemd -u root --hp /root | tail -1 | bash || true

echo "[10/10] Configurando Nginx y firewall..."
cat > "${NGINX_CONF}" <<EOF
server {
    listen 80;
    server_name ${SERVER_NAME};

    client_max_body_size 2m;

    location / {
        proxy_pass http://127.0.0.1:${APP_PORT};
        proxy_http_version 1.1;
        proxy_set_header Upgrade \$http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host \$host;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto \$scheme;
        proxy_cache_bypass \$http_upgrade;
    }
}
EOF

nginx -t
systemctl enable nginx
systemctl restart nginx

systemctl enable firewalld
systemctl start firewalld
firewall-cmd --permanent --add-service=http
firewall-cmd --permanent --add-service=https
firewall-cmd --reload

echo ""
echo "============================================"
echo " Despliegue completado"
echo "============================================"
echo " URL: http://${SERVER_NAME}"
echo " App:  ${APP_DIR}"
echo " Logs: ${LOG_DIR}"
echo ""
echo " Comandos útiles:"
echo "   pm2 status"
echo "   pm2 logs ${APP_NAME}"
echo "   pm2 restart ${APP_NAME}"
echo ""
echo " HTTPS (opcional): instalar certbot y ejecutar:"
echo "   yum install -y certbot python2-certbot-nginx"
echo "   certbot --nginx -d ${SERVER_NAME}"
echo "============================================"
