#!/bin/bash
# EXIM ERP Deployment Script
# Use this script to deploy updates to production

set -e

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

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

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

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

# Configuration
APP_DIR="/var/www/html/exim-erp"
BRANCH="${1:-main}"
MAINTENANCE_MODE=false

# Check if running as root or www-data
if [[ $EUID -eq 0 ]]; then
    print_warning "Running as root. Consider running as www-data user."
fi

print_status "Starting deployment on branch: $BRANCH"

cd "$APP_DIR"

# Enable maintenance mode
print_status "Enabling maintenance mode..."
php artisan down --render="errors::503" --retry=60 --secret="$(php artisan tinker --execute='echo Str::random(32);')" || true
MAINTENANCE_MODE=true

# Cleanup function
cleanup() {
    if [ "$MAINTENANCE_MODE" = true ]; then
        print_status "Disabling maintenance mode..."
        php artisan up
    fi
}
trap cleanup EXIT

# Pull latest changes
print_status "Pulling latest changes from $BRANCH..."
git fetch origin
git reset --hard "origin/$BRANCH"
git clean -fd

# Install dependencies
print_status "Installing composer dependencies..."
composer install --no-dev --optimize-autoloader --no-interaction

# Run database migrations
print_status "Running database migrations..."
php artisan migrate --force

# Seed database if needed (only in development)
if [ "$APP_ENV" = "local" ]; then
    print_status "Seeding database..."
    php artisan db:seed --force
fi

# Clear and cache configuration
print_status "Optimizing application..."
php artisan config:cache
php artisan route:cache
php artisan view:cache
php artisan event:cache
php artisan optimize

# Set proper permissions
print_status "Setting permissions..."
chown -R www-data:www-data "$APP_DIR"
chmod -R 755 "$APP_DIR"
chmod -R 775 "$APP_DIR/storage" 2>/dev/null || true
chmod -R 775 "$APP_DIR/bootstrap/cache" 2>/dev/null || true

# Restart services
print_status "Restarting services..."
systemctl restart php8.3-fpm 2>/dev/null || true
supervisorctl restart exim-erp-worker:* 2>/dev/null || true

# Disable maintenance mode
print_status "Disabling maintenance mode..."
php artisan up
MAINTENANCE_MODE=false

# Verify deployment
print_status "Verifying deployment..."
HTTP_STATUS=$(curl -s -o /dev/null -w "%{http_code}" http://localhost/ 2>/dev/null || echo "000")
if [ "$HTTP_STATUS" = "200" ] || [ "$HTTP_STATUS" = "302" ]; then
    print_status "Deployment successful! Application is responding."
else
    print_warning "Application returned HTTP $HTTP_STATUS. Please verify manually."
fi

echo ""
print_status "Deployment completed at $(date)"
echo "Application URL: https://$(hostname -f)"
