#!/bin/bash
# ============================================================
# CETERIS Connect - Initialisation serveur d'homologation
# Usage: ssh ceterisprime@ns3190545.ip-135-125-105.eu
#        bash setup-staging-server.sh
#
# Pre-requis: PHP 8.2, Python 3.11, Node 18, MySQL 8, Redis, Apache
# ============================================================

set -e

# Configuration
DEPLOY_ROOT="/home/ceterisprime/public_html/app/connect"
USER="ceterisprime"
GROUP="ceterisprime"
STAGING_DOMAIN="staging-connect.estair.travel"

# Couleurs
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

log_info()  { echo -e "${GREEN}[INFO]${NC} $1"; }
log_warn()  { echo -e "${YELLOW}[WARN]${NC} $1"; }
log_error() { echo -e "${RED}[ERROR]${NC} $1"; }
log_step()  { echo -e "${BLUE}[STEP]${NC} $1"; }

# ============================================================
# 1. ARBORESCENCE
# ============================================================
log_step "1/8 - Creation de l'arborescence..."

mkdir -p "$DEPLOY_ROOT"/{auth,estair,chaps,messager,spc-last,ftp_air,chaps-design}
mkdir -p "$DEPLOY_ROOT"/logs
mkdir -p "$DEPLOY_ROOT"/backups
mkdir -p "$DEPLOY_ROOT"/scripts

log_info "Arborescence creee dans $DEPLOY_ROOT"

# ============================================================
# 2. BASES DE DONNEES MySQL
# ============================================================
log_step "2/8 - Configuration des bases de donnees..."

# Generer un mot de passe aleatoire
STAGING_DB_PASSWORD=$(openssl rand -base64 24 | tr -dc 'a-zA-Z0-9' | head -c 32)

cat << 'SQLEOF' > /tmp/setup-staging-db.sql
-- Bases de donnees staging (deja creees via l'hebergeur)
-- ceterisprime_auth, ceterisprime_estair, ceterisprime_chaps, ceterisprime_messager
-- Utilisateur : ceterisprime_connect

-- S'assurer que les privileges sont corrects
GRANT ALL PRIVILEGES ON ceterisprime_auth.* TO 'ceterisprime_connect'@'localhost';
GRANT ALL PRIVILEGES ON ceterisprime_estair.* TO 'ceterisprime_connect'@'localhost';
GRANT ALL PRIVILEGES ON ceterisprime_chaps.* TO 'ceterisprime_connect'@'localhost';
GRANT ALL PRIVILEGES ON ceterisprime_messager.* TO 'ceterisprime_connect'@'localhost';
FLUSH PRIVILEGES;
SQLEOF

# Remplacer le placeholder par le vrai mot de passe
sed -i "s/STAGING_PASSWORD/$STAGING_DB_PASSWORD/g" /tmp/setup-staging-db.sql

log_warn "Executez le SQL suivant en tant que root MySQL :"
echo "  sudo mysql < /tmp/setup-staging-db.sql"
echo ""
log_info "Mot de passe staging genere : $STAGING_DB_PASSWORD"
echo "$STAGING_DB_PASSWORD" > "$DEPLOY_ROOT/.db_password"
chmod 600 "$DEPLOY_ROOT/.db_password"
log_info "Mot de passe sauvegarde dans $DEPLOY_ROOT/.db_password"

# ============================================================
# 3. CONFIGURATION APACHE
# ============================================================
log_step "3/8 - Configuration Apache..."

cat << APACHEEOF > "$DEPLOY_ROOT/scripts/apache-staging.conf"
# ============================================================
# CETERIS Connect - Configuration Apache Homologation
# A copier dans /etc/httpd/conf.d/ceteris-staging.conf
# Pre-requis: mod_proxy, mod_rewrite, mod_proxy_http actifs
# ============================================================

# ---- AUTH Service (port 8001) ----
Listen 8001
<VirtualHost *:8001>
    DocumentRoot $DEPLOY_ROOT/auth/public
    DirectoryIndex index.php

    <Directory $DEPLOY_ROOT/auth/public>
        AllowOverride All
        Require all granted
        Options -Indexes +FollowSymLinks

        RewriteEngine On
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteRule ^ index.php [L]
    </Directory>

    <DirectoryMatch "/\.">
        Require all denied
    </DirectoryMatch>

    ErrorLog /var/log/httpd/staging-auth-error.log
    CustomLog /var/log/httpd/staging-auth-access.log combined
</VirtualHost>

# ---- ESTAIR Service (port 8000) ----
Listen 8000
<VirtualHost *:8000>
    DocumentRoot $DEPLOY_ROOT/estair/public
    DirectoryIndex index.php

    LimitRequestBody 52428800

    <Directory $DEPLOY_ROOT/estair/public>
        AllowOverride All
        Require all granted
        Options -Indexes +FollowSymLinks

        RewriteEngine On
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteRule ^ index.php [L]
    </Directory>

    <DirectoryMatch "/\.">
        Require all denied
    </DirectoryMatch>

    TimeOut 600

    ErrorLog /var/log/httpd/staging-estair-error.log
    CustomLog /var/log/httpd/staging-estair-access.log combined
</VirtualHost>

# ---- CHAPS Service (port 8003) ----
Listen 8003
<VirtualHost *:8003>
    DocumentRoot $DEPLOY_ROOT/chaps/public
    DirectoryIndex index.php

    <Directory $DEPLOY_ROOT/chaps/public>
        AllowOverride All
        Require all granted
        Options -Indexes +FollowSymLinks

        RewriteEngine On
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteRule ^ index.php [L]
    </Directory>

    <DirectoryMatch "/\.">
        Require all denied
    </DirectoryMatch>

    ErrorLog /var/log/httpd/staging-chaps-error.log
    CustomLog /var/log/httpd/staging-chaps-access.log combined
</VirtualHost>

# ---- MESSAGER Service (port 8002) ----
Listen 8002
<VirtualHost *:8002>
    DocumentRoot $DEPLOY_ROOT/messager/public
    DirectoryIndex index.php

    <Directory $DEPLOY_ROOT/messager/public>
        AllowOverride All
        Require all granted
        Options -Indexes +FollowSymLinks

        RewriteEngine On
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteRule ^ index.php [L]
    </Directory>

    <DirectoryMatch "/\.">
        Require all denied
    </DirectoryMatch>

    ErrorLog /var/log/httpd/staging-messager-error.log
    CustomLog /var/log/httpd/staging-messager-access.log combined
</VirtualHost>

# ---- SPC-Last (reverse proxy vers Gunicorn port 5000) ----
Listen 5050
<VirtualHost *:5050>
    ProxyPreserveHost On
    ProxyPass / http://127.0.0.1:5000/
    ProxyPassReverse / http://127.0.0.1:5000/

    ProxyTimeout 600

    ErrorLog /var/log/httpd/staging-spc-error.log
    CustomLog /var/log/httpd/staging-spc-access.log combined
</VirtualHost>

# ---- Frontend Angular (fichiers statiques) ----
<VirtualHost *:80>
    ServerName $STAGING_DOMAIN

    DocumentRoot $DEPLOY_ROOT/chaps-design/dist/ESTAIR/browser
    DirectoryIndex index.html

    <Directory $DEPLOY_ROOT/chaps-design/dist/ESTAIR/browser>
        AllowOverride All
        Require all granted
        Options -Indexes +FollowSymLinks

        # SPA routing : toutes les routes vers index.html
        RewriteEngine On
        RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR]
        RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d
        RewriteRule ^.*$ - [NC,L]
        RewriteRule ^(?!.*\.).*$ index.html [NC,L]
    </Directory>

    # Proxy API vers les backends
    ProxyPreserveHost On

    # CHAPS API
    ProxyPass /api/ http://127.0.0.1:8003/api/
    ProxyPassReverse /api/ http://127.0.0.1:8003/api/

    # ESTAIR API
    ProxyPass /v1/ http://127.0.0.1:8000/v1/
    ProxyPassReverse /v1/ http://127.0.0.1:8000/v1/

    ErrorLog /var/log/httpd/staging-frontend-error.log
    CustomLog /var/log/httpd/staging-frontend-access.log combined
</VirtualHost>
APACHEEOF

log_info "Config Apache generee : $DEPLOY_ROOT/scripts/apache-staging.conf"
log_warn "A installer : sudo cp $DEPLOY_ROOT/scripts/apache-staging.conf /etc/httpd/conf.d/ceteris-staging.conf && sudo systemctl reload httpd"

# ============================================================
# 4. SUPERVISOR (Workers ESTAIR et MESSAGER)
# ============================================================
log_step "4/8 - Configuration Supervisor..."

cat << SUPEOF > "$DEPLOY_ROOT/scripts/ceteris-staging-workers.conf"
; ============================================================
; CETERIS Connect - Supervisor Workers Homologation
; A copier dans /etc/supervisord.d/ceteris-staging.ini
; ============================================================

[program:staging-estair-worker]
command=php $DEPLOY_ROOT/estair/artisan queue:work redis --sleep=3 --tries=3 --max-time=3600 --queue=financial_requests,air_processing,bsp_processing,default
user=$USER
numprocs=2
process_name=%(program_name)s_%(process_num)02d
autostart=true
autorestart=true
startsecs=5
startretries=3
stopwaitsecs=60
stdout_logfile=$DEPLOY_ROOT/logs/estair-worker-%(process_num)02d.log
stderr_logfile=$DEPLOY_ROOT/logs/estair-worker-%(process_num)02d-error.log
stdout_logfile_maxbytes=10MB
stdout_logfile_backups=3

[program:staging-messager-worker]
command=php $DEPLOY_ROOT/messager/artisan queue:work --sleep=3 --tries=6 --max-time=3600
user=$USER
numprocs=2
process_name=%(program_name)s_%(process_num)02d
autostart=true
autorestart=true
startsecs=5
startretries=3
stopwaitsecs=60
stdout_logfile=$DEPLOY_ROOT/logs/messager-worker-%(process_num)02d.log
stderr_logfile=$DEPLOY_ROOT/logs/messager-worker-%(process_num)02d-error.log
stdout_logfile_maxbytes=10MB
stdout_logfile_backups=3

[program:staging-ftp-air]
command=$DEPLOY_ROOT/ftp_air/venv/bin/python $DEPLOY_ROOT/ftp_air/advanced_ftp_watcher.py
user=$USER
numprocs=1
process_name=%(program_name)s
autostart=true
autorestart=true
startsecs=5
startretries=3
stopwaitsecs=10
stdout_logfile=$DEPLOY_ROOT/logs/ftp-air.log
stderr_logfile=$DEPLOY_ROOT/logs/ftp-air-error.log
stdout_logfile_maxbytes=10MB
stdout_logfile_backups=3
SUPEOF

log_info "Config Supervisor generee : $DEPLOY_ROOT/scripts/ceteris-staging-workers.conf"
log_warn "A installer : sudo cp $DEPLOY_ROOT/scripts/ceteris-staging-workers.conf /etc/supervisord.d/ceteris-staging.ini && sudo supervisorctl reread && sudo supervisorctl update"

# ============================================================
# 5. CRON (Laravel Scheduler)
# ============================================================
log_step "5/8 - Configuration Cron..."

CRON_CONTENT="# CETERIS Connect Staging - Laravel Scheduler
* * * * * cd $DEPLOY_ROOT/estair && php artisan schedule:run >> /dev/null 2>&1
* * * * * cd $DEPLOY_ROOT/chaps && php artisan schedule:run >> /dev/null 2>&1
* * * * * cd $DEPLOY_ROOT/messager && php artisan schedule:run >> /dev/null 2>&1"

echo "$CRON_CONTENT" > "$DEPLOY_ROOT/scripts/staging-crontab.txt"
log_info "Crontab genere : $DEPLOY_ROOT/scripts/staging-crontab.txt"
log_warn "A installer : crontab -l | cat - $DEPLOY_ROOT/scripts/staging-crontab.txt | crontab -"

# ============================================================
# 6. SPC-LAST (Python venv + systemd)
# ============================================================
log_step "6/8 - Configuration SPC-LAST..."

cat << SYSEOF > "$DEPLOY_ROOT/scripts/spc-flask-staging.service"
[Unit]
Description=SPC-LAST Flask API (Staging)
After=network.target

[Service]
User=$USER
WorkingDirectory=$DEPLOY_ROOT/spc-last
Environment="PATH=$DEPLOY_ROOT/spc-last/venv/bin:/usr/local/bin:/usr/bin"
ExecStart=$DEPLOY_ROOT/spc-last/venv/bin/gunicorn --bind 0.0.0.0:5000 --workers 2 --timeout 600 v2.api.flask_server:app
Restart=always
RestartSec=5

[Install]
WantedBy=multi-user.target
SYSEOF

log_info "Service systemd genere : $DEPLOY_ROOT/scripts/spc-flask-staging.service"
log_warn "A installer :"
echo "  sudo cp $DEPLOY_ROOT/scripts/spc-flask-staging.service /etc/systemd/system/"
echo "  sudo systemctl daemon-reload"
echo "  sudo systemctl enable spc-flask-staging"

# ============================================================
# 7. LOG ROTATION
# ============================================================
log_step "7/8 - Configuration Log Rotation..."

cat << LOGEOF > "$DEPLOY_ROOT/scripts/ceteris-staging-logrotate"
$DEPLOY_ROOT/*/storage/logs/*.log
$DEPLOY_ROOT/logs/*.log {
    daily
    missingok
    rotate 14
    compress
    delaycompress
    notifempty
    create 0640 $USER $GROUP
    sharedscripts
    postrotate
        # Restart workers pour liberer les handles de fichiers
        supervisorctl restart staging-estair-worker:* staging-messager-worker:* > /dev/null 2>&1 || true
    endscript
}
LOGEOF

log_info "Logrotate genere : $DEPLOY_ROOT/scripts/ceteris-staging-logrotate"
log_warn "A installer : sudo cp $DEPLOY_ROOT/scripts/ceteris-staging-logrotate /etc/logrotate.d/ceteris-staging"

# ============================================================
# 8. PERMISSIONS
# ============================================================
log_step "8/8 - Ajustement des permissions..."

chown -R "$USER:$GROUP" "$DEPLOY_ROOT"
chmod -R 755 "$DEPLOY_ROOT"

log_info "Permissions ajustees"

# ============================================================
# RESUME
# ============================================================
echo ""
echo "============================================================"
echo " SETUP TERMINE - Actions manuelles restantes :"
echo "============================================================"
echo ""
echo " 1. Creer les bases de donnees :"
echo "    sudo mysql < /tmp/setup-staging-db.sql"
echo ""
echo " 2. Installer la config Apache :"
echo "    sudo cp $DEPLOY_ROOT/scripts/apache-staging.conf /etc/httpd/conf.d/ceteris-staging.conf"
echo "    sudo systemctl reload httpd"
echo ""
echo " 3. Installer les workers Supervisor :"
echo "    sudo cp $DEPLOY_ROOT/scripts/ceteris-staging-workers.conf /etc/supervisord.d/ceteris-staging.ini"
echo "    sudo supervisorctl reread && sudo supervisorctl update"
echo ""
echo " 4. Installer le cron :"
echo "    crontab -l | cat - $DEPLOY_ROOT/scripts/staging-crontab.txt | crontab -"
echo ""
echo " 5. Installer le service SPC-LAST :"
echo "    sudo cp $DEPLOY_ROOT/scripts/spc-flask-staging.service /etc/systemd/system/"
echo "    sudo systemctl daemon-reload && sudo systemctl enable spc-flask-staging"
echo ""
echo " 6. Installer le logrotate :"
echo "    sudo cp $DEPLOY_ROOT/scripts/ceteris-staging-logrotate /etc/logrotate.d/ceteris-staging"
echo ""
echo " 7. Cloner chaque repo dans le dossier correspondant"
echo ""
echo " 8. Executer deploy-staging.sh all pour le premier deploiement"
echo ""
echo " Mot de passe DB staging : $(cat $DEPLOY_ROOT/.db_password)"
echo "============================================================"
