#!/bin/bash
# Start.sh - Local Service Management and Initialization Script

# Exit immediately if a command exits with a non-zero status
set -e

# Determine the server type (default: staging)
Servertype="staging"
if [ "$1" = "live" ] || [ "$1" = "production" ]; then
    Servertype="live"
fi

echo "============================================="
echo "Starting local deployment in [$Servertype] mode"
echo "============================================="

# 1. Load correct environment file
if [ "$Servertype" = "live" ]; then
    ENV_FILE="/var/www/secure/local/.env.live"
else
    ENV_FILE="/var/www/secure/local/.env.staging"
fi

if [ -f "$ENV_FILE" ]; then
    echo "Loading environment variables from $ENV_FILE..."
    # Export env vars from the env file, ignoring comments and empty lines
    export $(grep -v '^#' "$ENV_FILE" | grep -v '^[[:space:]]*$' | xargs)
else
    echo "❌ Environment file $ENV_FILE not found!"
    exit 1
fi

# Ensure SERVER_TYPE is set correctly for node_api config loading
if [ "$Servertype" = "live" ]; then
    export SERVER_TYPE="production"
else
    export SERVER_TYPE="staging"
fi

# 2. Check and start system services
check_and_start_service() {
    local svc=$1
    echo "Checking service status: $svc..."
    if ! systemctl is-active --quiet "$svc"; then
        echo "⚠️ Service $svc is stopped. Attempting to start..."
        systemctl start "$svc"
        if ! systemctl is-active --quiet "$svc"; then
            echo "❌ Failed to start $svc!"
        else
            echo "✅ Successfully started $svc."
        fi
    else
        echo "✅ Service $svc is running."
    fi
}

# Check all required local services
check_and_start_service "mysql"
check_and_start_service "redis-server"
check_and_start_service "cron"
check_and_start_service "php8.3-fpm"
check_and_start_service "apache2"

# Ensure the wildcard database user exists to prevent DEFINER errors in imported views
if [ -n "$MYSQL_ROOT_PASSWORD" ] && [ -n "$MYSQL_USER" ] && [ -n "$MYSQL_PASSWORD" ]; then
    echo "Ensuring MySQL wildcard user exists..."
    mysql -u root -p"${MYSQL_ROOT_PASSWORD}" -e "CREATE USER IF NOT EXISTS '${MYSQL_USER}'@'%' IDENTIFIED BY '${MYSQL_PASSWORD}'; GRANT ALL PRIVILEGES ON *.* TO '${MYSQL_USER}'@'%'; FLUSH PRIVILEGES;" 2>/dev/null || echo "⚠️ Warning: Failed to create MySQL wildcard user (MySQL might be starting up)."
fi

# 3. Setup uploads and logs directory permissions
echo "Setting up directory permissions..."
mkdir -p /var/www/html/public/logdata
mkdir -p /var/www/html/public/uploads
chmod -R 777 /var/www/html/public/logdata /var/www/html/public/uploads
chmod +x /var/www/html/docker/cron/*.sh
touch /var/www/html/public/api/trading_status.php
chmod -R 777 /var/www/html/public/uploads/backup
chmod 777 /var/www/html/public/api/trading_status.php

# 4. Manage html symlink
# Commented out because this creates a circular symlink and deletes the actual folder
# if [ -d "/var/www/html" ] && [ ! -L "/var/www/html" ]; then
#     BACKUP_NAME="/var/www/html_backup_$(date +%Y%m%d_%H%M%S)"
#     echo "Backing up existing /var/www/html folder to $BACKUP_NAME..."
#     mv /var/www/html "$BACKUP_NAME"
# fi

# if [ ! -L "/var/www/html" ]; then
#     echo "Creating symlink /var/www/html -> /var/www/html..."
#     ln -sf /var/www/html /var/www/html
# fi

# 5. Setup Cron Jobs
echo "Cleaning all existing user crontabs..."
crontab -r || true

if [ "$Servertype" = "live" ]; then
    CRON_SRC="/var/www/html/docker/cron/crontab-set-live.txt"
else
    CRON_SRC="/var/www/html/docker/cron/crontab-set.txt"
fi

if [ -f "$CRON_SRC" ]; then
    echo "Generating and installing local crontab from $CRON_SRC..."
    TEMP_CRON=$(mktemp)
    
    # Translate container paths and php binary paths to host paths
    sed -e 's|/usr/local/bin/php|/usr/bin/php|g' \
        -e 's|/var/www/html|/var/www/html|g' \
        "$CRON_SRC" > "$TEMP_CRON"
    
    crontab "$TEMP_CRON"
    rm -f "$TEMP_CRON"
    echo "✅ Local crontab successfully installed."
else
    echo "⚠️ Warning: Crontab source file $CRON_SRC not found!"
fi

# 6. PM2 Clean and Re-initialization
echo "Cleaning up all PM2 services..."
pm2 delete all || true
pm2 kill || true

echo "Starting local Node.js APIs and Websockets in PM2..."
cd /var/www/html/node_api
pm2 start ecosystem.api.config.js
pm2 start ecosystem.ws.config.js
pm2 save

# 7. Reload Apache Web Server
echo "Re-applying Apache configurations..."
# Disable old conflicting site configs (Docker-era Caddy proxy)
systemctl reload apache2

# 8. Start Background PHP Workers Immediately
echo "Starting PHP Background Workers..."
/bin/bash /var/www/html/docker/cron/run-workers.sh

echo "============================================="
echo "🎉 Deployment successfully completed!"
echo "============================================="
