#!/bin/bash

# HoofScan Swiss-Galoppers Deployment Script
# Target: app1.fr.vps.apmin.ch

set -e

echo "🚀 Starting deployment for app1.fr.vps.apmin.ch..."

# Configuration
SERVER_USER="root"
SERVER_HOST="app1.fr.vps.apmin.ch"
SERVER_PATH="/var/www/hoofscan"
DEPLOYMENT_PACKAGE="hoofscan-swiss-galoppers-deployment.tar.gz"

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

log_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# Step 1: Build production package
log_info "Building production package..."
if ! node build-production.js; then
    log_error "Production build failed"
    exit 1
fi

# Step 2: Create deployment archive
log_info "Creating deployment archive..."
cd deployment
tar -czf "../$DEPLOYMENT_PACKAGE" .
cd ..

# Step 3: Upload to server
log_info "Uploading to server..."
scp "$DEPLOYMENT_PACKAGE" "$SERVER_USER@$SERVER_HOST:/tmp/"

# Step 4: Deploy on server
log_info "Deploying on server..."
ssh "$SERVER_USER@$SERVER_HOST" << EOF
    set -e
    
    # Backup existing deployment
    if [ -d "$SERVER_PATH" ]; then
        log_info "Backing up existing deployment..."
        sudo cp -r "$SERVER_PATH" "$SERVER_PATH.backup.\$(date +%Y%m%d_%H%M%S)"
    fi
    
    # Create directory structure
    sudo mkdir -p "$SERVER_PATH"
    
    # Extract new deployment
    cd "$SERVER_PATH"
    sudo tar -xzf "/tmp/$DEPLOYMENT_PACKAGE"
    
    # Install dependencies
    log_info "Installing dependencies..."
    sudo npm install --production
    
    # Set permissions
    sudo chown -R www-data:www-data "$SERVER_PATH"
    sudo chmod -R 755 "$SERVER_PATH"
    
    # Restart services
    log_info "Restarting services..."
    sudo systemctl restart nginx
    sudo pm2 restart hoofscan-swiss-galoppers || sudo pm2 start "$SERVER_PATH/ecosystem.config.js"
    
    # Cleanup
    rm -f "/tmp/$DEPLOYMENT_PACKAGE"
    
    log_info "Deployment completed successfully!"
EOF

# Step 5: Health check
log_info "Performing health check..."
sleep 5

if curl -f -s https://app1.fr.vps.apmin.ch/api/health > /dev/null; then
    log_info "✅ Health check passed - app1.fr.vps.apmin.ch is running"
else
    log_warn "⚠️  Health check failed - please check server logs"
fi

# Cleanup local files
rm -f "$DEPLOYMENT_PACKAGE"

log_info "🎉 Deployment to app1.fr.vps.apmin.ch completed!"
echo ""
echo "🌐 Application URL: https://app1.fr.vps.apmin.ch"
echo "🔍 Health Check: https://app1.fr.vps.apmin.ch/api/health"
echo "👨‍💼 Admin Login: admin@swiss-galoppers.com / test123"
echo ""