#!/bin/bash
# Script de despliegue automático para WhatsApp Bot Manager
# Uso: ./deploy.sh [dominio] [usuario_db] [password_db]

echo "🚀 Iniciando despliegue de WhatsApp Bot Manager..."

# Validar parámetros
if [ $# -ne 3 ]; then
    echo "❌ Error: Faltan parámetros"
    echo "Uso: $0 <dominio> <usuario_db> <password_db>"
    echo "Ejemplo: $0 midominio.com db_user mi_password"
    exit 1
fi

DOMAIN=$1
DB_USER=$2
DB_PASS=$3
PROJECT_PATH="/var/www/html/bot"

echo "📋 Configuración:"
echo "   Dominio: $DOMAIN"
echo "   Usuario DB: $DB_USER"
echo "   Ruta: $PROJECT_PATH"

# Crear directorio del proyecto
echo "📁 Creando directorios..."
sudo mkdir -p $PROJECT_PATH
cd $PROJECT_PATH

# Configurar archivo de configuración
echo "⚙️  Configurando config.php..."
cat > config/config.php << EOF
<?php
/**
 * Configuración de producción - WhatsApp Bot Manager
 * Generado automáticamente: $(date)
 */

// Base de datos de producción
define('DB_HOST', 'localhost');
define('DB_NAME', 'whatsapp');
define('DB_USER', '$DB_USER');
define('DB_PASS', '$DB_PASS');
define('DB_CHARSET', 'utf8mb4');

// WhatsApp Business API (ACTUALIZAR CON TUS TOKENS)
define('WHATSAPP_TOKEN', 'TU_TOKEN_AQUI');
define('WHATSAPP_PHONE_NUMBER_ID', 'TU_PHONE_ID_AQUI');
define('WHATSAPP_API_URL', 'https://graph.facebook.com/v22.0/');
define('WEBHOOK_VERIFY_TOKEN', 'mi_token_secreto_123');

// Configuración de producción
define('APP_NAME', 'WhatsApp Bot Manager');
define('APP_VERSION', '1.0.0');
define('APP_URL', 'https://$DOMAIN/bot');
define('TIMEZONE', 'America/Bogota');

// Seguridad en producción
error_reporting(0);
ini_set('display_errors', 0);
ini_set('log_errors', 1);

// Headers de seguridad
header('X-Content-Type-Options: nosniff');
header('X-Frame-Options: DENY');
header('X-XSS-Protection: 1; mode=block');

// Autoloader
spl_autoload_register(function (\$class) {
    \$directories = [
        dirname(__DIR__) . '/classes/',
        dirname(__DIR__) . '/services/'
    ];
    
    foreach (\$directories as \$directory) {
        \$file = \$directory . \$class . '.php';
        if (file_exists(\$file)) {
            require_once \$file;
            return;
        }
    }
});
?>
EOF

# Crear .htaccess de seguridad
echo "🔒 Configurando seguridad..."
cat > .htaccess << EOF
RewriteEngine On

# Forzar HTTPS
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

# Proteger archivos sensibles
<Files "config.php">
    Require all denied
</Files>

<Files "*.sql">
    Require all denied
</Files>

<Files "*.log">
    Require all denied
</Files>

# Cache headers
<IfModule mod_expires.c>
    ExpiresActive on
    ExpiresByType text/css "access plus 1 year"
    ExpiresByType application/javascript "access plus 1 year"
    ExpiresByType image/png "access plus 1 year"
    ExpiresByType image/jpg "access plus 1 year"
</IfModule>

# Compresión GZIP
<IfModule mod_deflate.c>
    AddOutputFilterByType DEFLATE text/plain
    AddOutputFilterByType DEFLATE text/html
    AddOutputFilterByType DEFLATE text/css
    AddOutputFilterByType DEFLATE application/javascript
    AddOutputFilterByType DEFLATE application/json
</IfModule>
EOF

# Configurar permisos
echo "📝 Configurando permisos..."
sudo chown -R www-data:www-data $PROJECT_PATH
sudo find $PROJECT_PATH -type f -exec chmod 644 {} \;
sudo find $PROJECT_PATH -type d -exec chmod 755 {} \;
sudo chmod 600 $PROJECT_PATH/config/config.php

# Configurar Virtual Host de Apache
echo "🌐 Configurando Apache Virtual Host..."
sudo tee /etc/apache2/sites-available/whatsapp-bot.conf > /dev/null << EOF
<VirtualHost *:80>
    ServerName $DOMAIN
    ServerAlias www.$DOMAIN
    DocumentRoot $PROJECT_PATH
    
    <Directory $PROJECT_PATH>
        AllowOverride All
        Require all granted
        DirectoryIndex index.php
    </Directory>
    
    ErrorLog \${APACHE_LOG_DIR}/whatsapp-bot_error.log
    CustomLog \${APACHE_LOG_DIR}/whatsapp-bot_access.log combined
    
    # Redirigir HTTP a HTTPS
    RewriteEngine On
    RewriteCond %{HTTPS} off
    RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</VirtualHost>

<IfModule mod_ssl.c>
<VirtualHost *:443>
    ServerName $DOMAIN
    ServerAlias www.$DOMAIN
    DocumentRoot $PROJECT_PATH
    
    SSLEngine on
    SSLCertificateFile /etc/letsencrypt/live/$DOMAIN/fullchain.pem
    SSLCertificateKeyFile /etc/letsencrypt/live/$DOMAIN/privkey.pem
    
    <Directory $PROJECT_PATH>
        AllowOverride All
        Require all granted
        DirectoryIndex index.php
    </Directory>
    
    ErrorLog \${APACHE_LOG_DIR}/whatsapp-bot_ssl_error.log
    CustomLog \${APACHE_LOG_DIR}/whatsapp-bot_ssl_access.log combined
</VirtualHost>
</IfModule>
EOF

# Habilitar sitio
echo "✅ Habilitando sitio..."
sudo a2ensite whatsapp-bot.conf
sudo a2enmod rewrite ssl
sudo systemctl reload apache2

# Configurar SSL con Let's Encrypt
echo "🔐 Configurando SSL..."
if command -v certbot &> /dev/null; then
    sudo certbot --apache -d $DOMAIN -d www.$DOMAIN --non-interactive --agree-tos --email admin@$DOMAIN
else
    echo "⚠️  Certbot no instalado. Instala SSL manualmente:"
    echo "   sudo apt install certbot python3-certbot-apache"
    echo "   sudo certbot --apache -d $DOMAIN"
fi

# Crear base de datos
echo "🗄️  Configurando base de datos..."
sudo mysql -e "CREATE DATABASE IF NOT EXISTS whatsapp DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;"
sudo mysql -e "CREATE USER IF NOT EXISTS '$DB_USER'@'localhost' IDENTIFIED BY '$DB_PASS';"
sudo mysql -e "GRANT ALL PRIVILEGES ON whatsapp.* TO '$DB_USER'@'localhost';"
sudo mysql -e "FLUSH PRIVILEGES;"

# Crear script de backup
echo "💾 Configurando backup automático..."
sudo tee /usr/local/bin/backup-whatsapp.sh > /dev/null << EOF
#!/bin/bash
DATE=\$(date +%Y%m%d_%H%M%S)
BACKUP_DIR="/var/backups/whatsapp"
mkdir -p \$BACKUP_DIR

# Backup de base de datos
mysqldump -u $DB_USER -p'$DB_PASS' whatsapp > \$BACKUP_DIR/whatsapp_\$DATE.sql

# Backup de archivos
tar -czf \$BACKUP_DIR/files_\$DATE.tar.gz $PROJECT_PATH

# Eliminar backups antiguos (más de 7 días)
find \$BACKUP_DIR -name "*.sql" -mtime +7 -delete
find \$BACKUP_DIR -name "*.tar.gz" -mtime +7 -delete

echo "Backup completado: \$DATE"
EOF

sudo chmod +x /usr/local/bin/backup-whatsapp.sh

# Configurar cron para backup diario
echo "⏰ Configurando backup automático diario..."
(crontab -l 2>/dev/null; echo "0 2 * * * /usr/local/bin/backup-whatsapp.sh") | crontab -

# Mostrar información final
echo ""
echo "🎉 ¡Despliegue completado!"
echo ""
echo "📋 Información importante:"
echo "   🌐 Sitio web: https://$DOMAIN/migrador"
echo "   ⚙️  Instalador: https://$DOMAIN/migrador/install.php"
echo "   🧪 Pruebas: https://$DOMAIN/migrador/test.php"
echo "   📱 Webhook: https://$DOMAIN/migrador/api/webhook.php"
echo ""
echo "🔧 Próximos pasos:"
echo "   1. Edita config/config.php con tus tokens de WhatsApp"
echo "   2. Ejecuta el instalador: https://$DOMAIN/migrador/install.php"
echo "   3. Configura webhook en Facebook Developers"
echo "   4. Prueba el sistema: https://$DOMAIN/migrador/test.php"
echo ""
echo "📁 Rutas importantes:"
echo "   Config: $PROJECT_PATH/config/config.php"
echo "   Logs: /var/log/apache2/whatsapp-bot_*.log"
echo "   Backups: /var/backups/whatsapp/"
echo ""
echo "🔒 Webhook URL para Facebook:"
echo "   https://$DOMAIN/migrador/api/webhook.php"
echo "   Token de verificación: mi_token_secreto_123"
echo ""

# Verificar estado de servicios
echo "📊 Estado de servicios:"
sudo systemctl is-active apache2 && echo "   ✅ Apache: Funcionando" || echo "   ❌ Apache: Error"
sudo systemctl is-active mysql && echo "   ✅ MySQL: Funcionando" || echo "   ❌ MySQL: Error"

echo ""
echo "¡Tu WhatsApp Bot Manager está listo! 🚀"