#!/bin/bash

# ZARADIN Deployment Script for cPanel
# Usage: ./scripts/deploy.sh [dev|stage|prod]

set -e  # Exit on error

ENV=$1
if [ -z "$ENV" ]; then
    echo "Usage: $0 [dev|stage|prod]"
    exit 1
fi

# Map CircleCI environment variables to standard names
SSH_USER=${SSH_USER_TECHSANGA}
SSH_PORT=${SSH_PORT_SINGL:-22}

case $ENV in
    dev)
        DEPLOY_PATH=$DEV_DEPLOY_PATH
        ;;
    stage)
        DEPLOY_PATH=$STAGE_DEPLOY_PATH
        ;;
    prod)
        DEPLOY_PATH=$PROD_DEPLOY_PATH
        ;;
    *)
        echo "Invalid environment. Use dev, stage, or prod."
        exit 1
        ;;
esac

echo "========================================="
echo "Starting deployment to $ENV"
echo "========================================="
echo "SSH User: $SSH_USER"
echo "SSH Host: $SSH_HOST"
echo "SSH Port: $SSH_PORT"
echo "Deploy Path: $DEPLOY_PATH"
echo "========================================="

# Verify required environment variables
if [ -z "$SSH_USER" ] || [ -z "$SSH_HOST" ] || [ -z "$DEPLOY_PATH" ]; then
    echo "ERROR: Missing required environment variables"
    echo "Required: SSH_USER, SSH_HOST, DEPLOY_PATH"
    exit 1
fi

# Diagnostic: Test SSH connection and see what the shell outputs
echo "Step 0: Testing SSH connection..."
echo "--- BEGIN SSH OUTPUT ---"
ssh -p $SSH_PORT $SSH_USER@$SSH_HOST "echo 'SSH_TEST_SUCCESS'"
echo "--- END SSH OUTPUT ---"
echo ""

# Prepare Admin Dashboard (Static) locally in CircleCI
echo "Step 0.5: Preparing Admin Dashboard..."
echo "=== DEBUG: Checking admin-dashboard/dist ==="
ls -la admin-dashboard/ 2>/dev/null || echo "admin-dashboard folder not found"
ls -la admin-dashboard/dist/ 2>/dev/null || echo "admin-dashboard/dist folder not found"
ls -la admin-dashboard/dist/admin/ 2>/dev/null || echo "admin-dashboard/dist/admin folder not found"

if [ -d "admin-dashboard/dist" ]; then
    mkdir -p public/admin
    # Copy all contents from dist/ to public/admin/
    # This ensures _expo/ and assets/ folders (at root of dist) are included
    # which are required for the dashboard to function.
    echo "Copying all files from admin-dashboard/dist/ to public/admin/..."
    cp -r admin-dashboard/dist/* public/admin/
    
    # If a nested 'admin' folder exists, we might have public/admin/admin/
    # We want the contents of dist/admin/ to be at the root of public/admin/
    # though usually index.html at dist/ root is already correct.
    if [ -d "admin-dashboard/dist/admin" ]; then
        echo "Updating public/admin/ with contents from nested admin folder..."
        cp -r admin-dashboard/dist/admin/* public/admin/
    fi
    
    echo "=== DEBUG: Contents of public/admin after copy ==="
    ls -la public/admin/
    echo "Admin dashboard files prepared in public/admin/"
else
    echo "ERROR: admin-dashboard/dist not found! Build may have failed."
    echo "Checking if admin-dashboard exists:"
    ls -la admin-dashboard/ 2>/dev/null || echo "admin-dashboard folder missing entirely"
fi

# 1. Sync Files
echo "Step 1: Syncing files to server..."
rsync -avz --delete \
    --protocol=29 \
    --blocking-io \
    -e "ssh -p $SSH_PORT -q -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o LogLevel=ERROR" \
    --rsync-path="rsync" \
    --exclude '.git/' \
    --exclude '.circleci/' \
    --exclude '.agent/' \
    --exclude '.ssh/' \
    --exclude 'node_modules/' \
    --exclude 'vendor/' \
    --exclude 'storage/*.key' \
    --exclude '.env' \
    --exclude 'tests/' \
    --exclude 'phpunit.xml' \
    --exclude 'admin-dashboard/node_modules/' \
    --exclude 'admin-dashboard/dist/' \
    --exclude 'public-website/node_modules/' \
    --exclude 'public/admin/' \
    ./ $SSH_USER@$SSH_HOST:$DEPLOY_PATH/

echo "Step 1.5: Syncing admin dashboard to public/admin..."
if [ -d "public/admin" ] && [ "$(ls -A public/admin 2>/dev/null)" ]; then
    rsync -avz --delete \
        --protocol=29 \
        -e "ssh -p $SSH_PORT -q -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o LogLevel=ERROR" \
        --rsync-path="rsync" \
        public/admin/ $SSH_USER@$SSH_HOST:$DEPLOY_PATH/public/admin/
else
    echo "WARNING: public/admin is empty or missing locally. Skipping admin dashboard sync to avoid deleting remote files."
fi

echo "Step 2: Running remote commands..."

# 2. Run Remote Commands (Laravel)
ssh -p $SSH_PORT $SSH_USER@$SSH_HOST << EOF
    set -e
    cd $DEPLOY_PATH
    
    echo "Current directory: \$(pwd)"
    echo "Files in directory:"
    ls -la
    
    # Get the actual home directory on the remote server
    REMOTE_HOME=\$(eval echo ~\$USER)
    
    # Find the correct PHP CLI binary (cPanel uses ea-php in /opt/cpanel)
    echo "=== Finding PHP Binary ==="
    if [ -f "/opt/cpanel/ea-php83/root/usr/bin/php" ]; then
        PHP_BIN="/opt/cpanel/ea-php83/root/usr/bin/php"
        echo "Using PHP 8.3 CLI: \$PHP_BIN"
    elif [ -f "/opt/cpanel/ea-php82/root/usr/bin/php" ]; then
        PHP_BIN="/opt/cpanel/ea-php82/root/usr/bin/php"
        echo "Using PHP 8.2 CLI: \$PHP_BIN"
    elif [ -f "/opt/cpanel/ea-php81/root/usr/bin/php" ]; then
        PHP_BIN="/opt/cpanel/ea-php81/root/usr/bin/php"
        echo "Using PHP 8.1 CLI: \$PHP_BIN"
    elif [ -f "/usr/bin/php" ]; then
        PHP_BIN="/usr/bin/php"
        echo "Using system PHP CLI: \$PHP_BIN"
    else
        PHP_BIN="php"
        echo "Using default PHP: \$PHP_BIN"
    fi
    echo "=========================="
    echo ""
    
    # Debug: Check PHP configuration
    echo "=== PHP Debug Info ==="
    echo "PHP Version:"
    \$PHP_BIN -v
    echo ""
    echo "PHP Binary Location:"
    echo \$PHP_BIN
    echo "======================"
    echo ""
    
    # Find Composer - check common cPanel locations
    echo "Looking for Composer..."
    echo "Remote home directory: \$REMOTE_HOME"
    
    if [ -f "\$REMOTE_HOME/bin/composer" ]; then
        COMPOSER="\$REMOTE_HOME/bin/composer"
        echo "Found existing Composer at: \$COMPOSER"
    elif [ -f "\$REMOTE_HOME/.composer/composer" ]; then
        COMPOSER="\$REMOTE_HOME/.composer/composer"
        echo "Found existing Composer at: \$COMPOSER"
    elif [ -f "/usr/local/bin/composer" ]; then
        COMPOSER="/usr/local/bin/composer"
        echo "Found existing Composer at: \$COMPOSER"
    elif [ -f "/usr/bin/composer" ]; then
        COMPOSER="/usr/bin/composer"
        echo "Found existing Composer at: \$COMPOSER"
    elif command -v composer &> /dev/null; then
        COMPOSER="composer"
        echo "Found Composer in PATH"
    else
        echo "WARNING: Composer not found, attempting to download..."
        mkdir -p "\$REMOTE_HOME/bin"
        cd "\$REMOTE_HOME/bin"
        
        # Download composer.phar directly
        echo "Downloading Composer..."
        if curl -sS https://getcomposer.org/download/latest-stable/composer.phar -o composer; then
            chmod +x composer
            echo "Successfully downloaded Composer"
        else
            echo "ERROR: Could not download Composer"
            echo "Please install Composer manually on the server:"
            echo "  cd \$REMOTE_HOME/bin"
            echo "  curl -sS https://getcomposer.org/download/latest-stable/composer.phar -o composer"
            echo "  chmod +x composer"
            exit 1
        fi
        
        cd "$DEPLOY_PATH"
        COMPOSER="\$REMOTE_HOME/bin/composer"
    fi
    
    echo "Using Composer: \$COMPOSER"
    echo "Composer version:"
    \$PHP_BIN \$COMPOSER --version 2>&1 || echo "WARNING: Could not get Composer version"
    echo ""
    
    # Install dependencies (on server)
    echo "Installing Composer dependencies..."
    \$PHP_BIN \$COMPOSER install --no-dev --optimize-autoloader --no-interaction
    
    # Generate APP_KEY if .env exists but APP_KEY is empty
    if [ -f ".env" ]; then
        if ! grep -q "APP_KEY=base64:" .env 2>/dev/null; then
            echo "Generating APP_KEY..."
            \$PHP_BIN artisan key:generate --force
            echo "APP_KEY generated successfully"
        else
            echo "APP_KEY already exists"
        fi
    else
        echo "WARNING: .env file not found. Please create it manually with database credentials."
    fi
    
    # Run migrations
    echo "Running migrations..."
    \$PHP_BIN artisan migrate --force
    
    # Run essential seeders (only if tables are empty or need updates)
    echo "Running essential seeders..."
    \$PHP_BIN artisan db:seed --class=PlansSeeder --force 2>/dev/null || echo "PlansSeeder already run"
    \$PHP_BIN artisan db:seed --class=MasterDataSeeder --force 2>/dev/null || echo "MasterDataSeeder already run"
    \$PHP_BIN artisan db:seed --class=SuperAdminSeeder --force 2>/dev/null || echo "SuperAdminSeeder skipped"
    \$PHP_BIN artisan db:seed --class=DemoTenantSeeder --force 2>/dev/null || echo "DemoTenantSeeder skipped"
    
    # Ensure storage directories exist
    echo "Setting up storage directories..."
    mkdir -p storage/framework/cache/data
    mkdir -p storage/framework/sessions
    mkdir -p storage/framework/views
    mkdir -p storage/logs
    chmod -R 775 storage
    chmod -R 775 bootstrap/cache
    
    # Optimize caches
    echo "Optimizing Laravel caches..."
    \$PHP_BIN artisan config:cache
    \$PHP_BIN artisan route:cache
    
    # Handle Next.js (if applicable)
    if [ -d "public-website" ]; then
        echo "Next.js build artifacts synced successfully"
        # Build is already done by CircleCI and synced via rsync
        # If using PM2 for Next.js, restart here:
        # cd public-website && pm2 restart zaradin-$ENV
    else
        echo "WARNING: public-website directory not found"
    fi
    
    echo "Remote commands completed successfully"
EOF

echo "========================================="
echo "Deployment to $ENV complete!"
echo "========================================="
