#!/usr/bin/env bash set -euo pipefail LOGFILE="/var/log/laravel_deploy.log" log() { echo "[$(date '+%Y-%m-%d %H:%M:%S')] $*" | tee -a "$LOGFILE" } rollback() { log "⚠️ Deployment failed — attempting rollback!" git reset --hard HEAD@{1} php artisan up || true log "Rollback complete." exit 1 } trap rollback ERR log "=== 🚀 Laravel Deployment Started ===" log "Checking for uncommitted changes..." if ! git diff --quiet || ! git diff --cached --quiet; then log "❌ Uncommitted changes detected. Aborting." exit 1 fi log "Putting application into maintenance mode..." php artisan down --render="errors::503" --retry=60 || true log "Pulling latest code..." git pull --rebase --autostash log "Restarting PHP-FPM..." systemctl restart php8.3-fpm.service log "Clearing old caches..." php artisan optimize:clear log "Rebuilding caches..." php artisan config:cache php artisan route:cache php artisan view:cache php artisan event:cache php artisan package:discover --ansi php artisan optimize log "Setting permissions safely..." find storage -type d -exec chmod 775 {} \; find storage -type f -exec chmod 664 {} \; find bootstrap/cache -type d -exec chmod 775 {} \; find bootstrap/cache -type f -exec chmod 664 {} \; chown -R www-data:www-data storage bootstrap/cache log "Restarting queue workers..." if ! pgrep -f "artisan queue:work" > /dev/null; then nohup php artisan queue:work --daemon --quiet >> /dev/null 2>&1 & log "Queue worker started." else log "Queue worker already running." fi log "Resetting OPcache if available..." php -r "if (function_exists('opcache_reset')) opcache_reset();" || true log "Bringing application back online..." php artisan up log "=== ✅ Deployment completed successfully ==="