#!/bin/bash
# ==============================================================================
# Automated Production Deployment Script for GOCO Technology
# Domain: https://www.gocotechnology.com
# ==============================================================================

set -e

echo "🚀 Starting Deployment for GOCO Technology..."

# 1. Enable Maintenance Mode
echo "🔒 Enabling maintenance mode..."
php artisan down || true

# 2. Fetch Latest Changes from Repository
echo "📥 Pulling latest updates from Git..."
git pull origin main

# 3. Install Composer Dependencies (Production Only)
echo "📦 Installing Composer dependencies..."
composer install --no-dev --optimize-autoloader --no-interaction

# 4. Run Database Migrations
echo "🗄️ Running database migrations..."
php artisan migrate --force

# 5. Optimize Caches
echo "⚡ Optimizing Laravel caches..."
php artisan config:cache
php artisan route:cache
php artisan view:cache
php artisan event:cache

# 6. Correct Permissions for Storage and Cache Directories
echo "🔐 Setting file permissions..."
sudo chown -R www-data:www-data /var/www/gocotechnology.com/storage /var/www/gocotechnology.com/public_html/bootstrap/cache
sudo chmod -R 775 /var/www/gocotechnology.com/storage /var/www/gocotechnology.com/public_html/bootstrap/cache

# 7. Reload Nginx and PHP-FPM
echo "🔄 Reloading web server..."
sudo systemctl reload nginx
sudo systemctl reload php8.2-fpm || true

# 8. Disable Maintenance Mode
echo "🔓 Disabling maintenance mode..."
php artisan up

echo "✅ Deployment completed successfully! Live site: https://www.gocotechnology.com"
