#!/bin/bash

# Production Deployment Script using Git Pull
# Mirrors deploy-beta.sh but targets production (/var/www/html on xeek.com).
# Usage: ./deploy-prod.sh [branch-name]
# If no branch specified, uses current branch.

SERVER="root@xeek.com"
DEPLOY_PATH="/var/www/html"

# Get current branch if not specified
if [ $# -eq 0 ]; then
    BRANCH=$(git branch --show-current)
    echo "No branch specified, using current branch: $BRANCH"
else
    BRANCH="$1"
fi

echo "🚀 Deploying branch '$BRANCH' to PRODUCTION ($SERVER:$DEPLOY_PATH)"
echo ""

# Extra confirmation — this is production.
read -p "⚠️  This deploys to PRODUCTION (xeek.com). Type 'deploy' to continue: " CONFIRM
if [ "$CONFIRM" != "deploy" ]; then
    echo "Aborted."
    exit 1
fi
echo ""

# Check if there are uncommitted changes
if ! git diff-index --quiet HEAD --; then
    echo "⚠️  Warning: You have uncommitted changes"
    read -p "Continue anyway? (y/n) " -n 1 -r
    echo
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        exit 1
    fi
fi

# Push current branch to GitHub
echo "📤 Pushing to GitHub..."
git push origin "$BRANCH"
if [ $? -ne 0 ]; then
    echo "❌ Git push failed!"
    exit 1
fi
echo "✅ Pushed to GitHub"
echo ""

# Back up the production database before touching anything.
echo "💾 Backing up production database..."
ssh "$SERVER" "cd $DEPLOY_PATH && ./backup_database.sh"
if [ $? -ne 0 ]; then
    echo "❌ Database backup failed — aborting before any changes."
    exit 1
fi
echo "✅ Backup complete"
echo ""

# Deploy on production server
echo "🔧 Deploying on production server..."
ssh "$SERVER" << ENDSSH
set -e

cd $DEPLOY_PATH

echo "📥 Pulling latest code from GitHub..."
git fetch origin
git checkout $BRANCH
git pull origin $BRANCH

echo "🔧 Installing dependencies..."
composer install --no-dev --optimize-autoloader --no-interaction

echo "📦 Building frontend assets..."
npm ci
npm run build

echo "🗄️  Running migrations..."
php artisan migrate --force

echo "🧹 Clearing caches..."
php artisan config:clear
php artisan view:clear
php artisan cache:clear
php artisan route:clear

echo "⚡ Caching for production..."
php artisan config:cache
php artisan view:cache
php artisan route:cache

echo "🔗 Ensuring storage link exists..."
php artisan storage:link || true

echo "🔄 Restarting queue workers..."
php artisan queue:restart

echo "🔐 Setting permissions..."
chmod -R 775 storage bootstrap/cache

echo "🔁 Reloading Apache..."
sudo systemctl reload apache2

echo "✅ Deployment complete!"
ENDSSH

if [ $? -eq 0 ]; then
    echo ""
    echo "🎉 Production deployment successful!"
    echo "🌐 Site: https://xeek.com"
else
    echo ""
    echo "❌ Deployment failed on server"
    exit 1
fi
