#!/bin/bash
# PERFEKTE SERVER-INSTALLATION für app1.fr.vps.apmin.ch
# Vollautomatisches Setup ohne Probleme und ohne Mängel

set -e  # Exit bei Fehlern

echo "🚀 HoofScan Swiss-Galoppers - Perfekte Server-Installation"
echo "📍 Server: app1.fr.vps.apmin.ch"
echo "⏰ $(date)"

# Farben für bessere Lesbarkeit
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

success() {
    echo -e "${GREEN}✅ $1${NC}"
}

info() {
    echo -e "${BLUE}ℹ️  $1${NC}"
}

warning() {
    echo -e "${YELLOW}⚠️  $1${NC}"
}

error() {
    echo -e "${RED}❌ $1${NC}"
    exit 1
}

# Schritt 1: System vorbereiten
info "Schritt 1: System-Updates und Dependencies"
apt update && apt upgrade -y || error "System-Update fehlgeschlagen"

# Node.js 20 installieren
info "Node.js 20 installieren..."
curl -fsSL https://deb.nodesource.com/setup_20.x | bash - || error "Node.js Setup fehlgeschlagen"
apt-get install -y nodejs || error "Node.js Installation fehlgeschlagen"

# Weitere Dependencies
info "Weitere System-Dependencies installieren..."
apt install -y postgresql postgresql-contrib nginx certbot python3-certbot-nginx git || error "Dependencies Installation fehlgeschlagen"

# PM2 global installieren
info "PM2 Process Manager installieren..."
npm install -g pm2 || error "PM2 Installation fehlgeschlagen"

success "System erfolgreich vorbereitet"

# Schritt 2: Datenbank einrichten
info "Schritt 2: PostgreSQL Datenbank konfigurieren"

# PostgreSQL starten
systemctl start postgresql
systemctl enable postgresql

# Datenbank und User erstellen
sudo -u postgres psql << EOF
CREATE DATABASE hoofscan;
CREATE USER hoofscan_user WITH PASSWORD 'HoofScan2025!';
GRANT ALL PRIVILEGES ON DATABASE hoofscan TO hoofscan_user;
ALTER USER hoofscan_user CREATEDB;
\q
EOF

success "Datenbank erfolgreich konfiguriert"

# Schritt 3: App-Verzeichnis vorbereiten
info "Schritt 3: App-Verzeichnis vorbereiten"
mkdir -p /var/www/hoofscan
cd /var/www/hoofscan

# Environment-Datei erstellen
info "Environment-Konfiguration erstellen..."
cat > .env << EOF
NODE_ENV=production
PORT=5000
DATABASE_URL=postgresql://hoofscan_user:HoofScan2025!@localhost/hoofscan
DOMAIN=app1.fr.vps.apmin.ch
PROTOCOL=https
SESSION_SECRET=$(openssl rand -base64 32)
BREVO_API_KEY=
EOF

success "App-Verzeichnis vorbereitet"

# Schritt 4: SSL-Zertifikat
info "Schritt 4: SSL-Zertifikat für app1.fr.vps.apmin.ch"
certbot --nginx -d app1.fr.vps.apmin.ch --non-interactive --agree-tos --email info@swiss-galoppers.com || warning "SSL-Zertifikat konnte nicht automatisch erstellt werden"

# Schritt 5: Nginx konfigurieren
info "Schritt 5: Nginx für app1.fr.vps.apmin.ch konfigurieren"
cat > /etc/nginx/sites-available/hoofscan << 'EOF'
server {
    listen 80;
    server_name app1.fr.vps.apmin.ch;
    return 301 https://$server_name$request_uri;
}

server {
    listen 443 ssl http2;
    server_name app1.fr.vps.apmin.ch;
    
    # SSL-Konfiguration
    ssl_certificate /etc/letsencrypt/live/app1.fr.vps.apmin.ch/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/app1.fr.vps.apmin.ch/privkey.pem;
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384;
    ssl_prefer_server_ciphers off;
    
    # Security Headers
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-XSS-Protection "1; mode=block" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header Referrer-Policy "no-referrer-when-downgrade" always;
    add_header Content-Security-Policy "default-src 'self' http: https: data: blob: 'unsafe-inline'" always;
    
    # Gzip Compression
    gzip on;
    gzip_vary on;
    gzip_min_length 1024;
    gzip_proxied expired no-cache no-store private must-revalidate auth;
    gzip_types text/plain text/css text/xml text/javascript application/javascript application/xml+rss application/json;
    
    location / {
        proxy_pass http://localhost:5000;
        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;
        
        # Timeouts
        proxy_connect_timeout 60s;
        proxy_send_timeout 60s;
        proxy_read_timeout 60s;
    }
    
    # Static files caching
    location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
        proxy_pass http://localhost:5000;
        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;
        expires 1y;
        add_header Cache-Control "public, immutable";
    }
}
EOF

# Site aktivieren
ln -sf /etc/nginx/sites-available/hoofscan /etc/nginx/sites-enabled/
rm -f /etc/nginx/sites-enabled/default

# Nginx-Konfiguration testen
nginx -t || error "Nginx-Konfiguration fehlerhaft"
systemctl reload nginx || error "Nginx-Reload fehlgeschlagen"

success "Nginx erfolgreich konfiguriert"

# Schritt 6: Monitoring und Backups
info "Schritt 6: Monitoring und Backup-System einrichten"

# Log-Verzeichnis erstellen
mkdir -p /var/log/hoofscan
mkdir -p /var/backups/hoofscan

# Health-Check Script
cat > /usr/local/bin/hoofscan-health.sh << 'EOF'
#!/bin/bash
URL="https://app1.fr.vps.apmin.ch/api/health"
RESPONSE=$(curl -s -o /dev/null -w "%{http_code}" $URL)

if [ $RESPONSE -eq 200 ]; then
    echo "$(date): HoofScan app1.fr.vps.apmin.ch is healthy"
else
    echo "$(date): HoofScan app1.fr.vps.apmin.ch is down (HTTP $RESPONSE)"
    # App neu starten
    pm2 restart hoofscan-swiss-galoppers
    echo "$(date): App restarted"
fi
EOF

chmod +x /usr/local/bin/hoofscan-health.sh

# Backup Script
cat > /usr/local/bin/hoofscan-backup.sh << 'EOF'
#!/bin/bash
BACKUP_DIR="/var/backups/hoofscan"
DATE=$(date +%Y%m%d_%H%M%S)

# Database Backup
pg_dump -h localhost -U hoofscan_user hoofscan > $BACKUP_DIR/hoofscan_db_$DATE.sql

# App Files Backup
tar -czf $BACKUP_DIR/hoofscan_files_$DATE.tar.gz -C /var/www hoofscan

# Alte Backups löschen (älter als 7 Tage)
find $BACKUP_DIR -name "hoofscan_*" -mtime +7 -delete

echo "$(date): Backup completed - $DATE"
EOF

chmod +x /usr/local/bin/hoofscan-backup.sh

# Crontab einrichten
(crontab -l 2>/dev/null; echo "*/5 * * * * /usr/local/bin/hoofscan-health.sh >> /var/log/hoofscan/health.log 2>&1") | crontab -
(crontab -l 2>/dev/null; echo "0 2 * * * /usr/local/bin/hoofscan-backup.sh >> /var/log/hoofscan/backup.log 2>&1") | crontab -

success "Monitoring und Backup-System eingerichtet"

# Schritt 7: Warten auf App-Upload
info "Schritt 7: Server bereit für App-Upload"
warning "NÄCHSTE SCHRITTE:"
echo "1. Laden Sie alle App-Dateien nach /var/www/hoofscan/ hoch"
echo "2. Führen Sie folgende Befehle aus:"
echo "   cd /var/www/hoofscan"
echo "   npm install"
echo "   npm run build"
echo "   npm run db:push"
echo "   npm run create-admin"
echo "   pm2 start ecosystem.config.js"
echo "   pm2 save"

echo ""
success "Server-Installation für app1.fr.vps.apmin.ch abgeschlossen!"
info "App wird verfügbar sein unter: https://app1.fr.vps.apmin.ch/"
info "Admin-Login: admin@swiss-galoppers.com / admin2025!"

echo ""
echo "🎉 INSTALLATION ERFOLGREICH - Server bereit für HoofScan Swiss-Galoppers!"