#!/usr/bin/env bash
# Zero-downtime-ish release: build in a new directory, switch the "current" symlink, restart workers.
# Usage (as deploy user): deploy/deploy.sh <git-ref>
set -euo pipefail
APP=/var/www/seo-platform; REF=${1:-main}; REL=$APP/releases/$(date +%Y%m%d%H%M%S)
git clone --depth 1 --branch "$REF" "$(git -C $APP/current remote get-url origin)" "$REL"
cd "$REL"
rm -rf storage && ln -s $APP/shared/storage storage
ln -s $APP/shared/.env .env
composer install --no-dev --prefer-dist --optimize-autoloader --no-interaction
npm ci --ignore-scripts && npm run build && rm -rf node_modules
php artisan migrate --force
php artisan optimize
ln -sfn "$REL" $APP/current
sudo systemctl reload php8.4-fpm
php artisan queue:restart          # workers finish their current job, then reload code
ls -1dt $APP/releases/* | tail -n +6 | xargs -r rm -rf   # keep 5 releases
echo "Deployed $REF -> $REL"
