#!/usr/bin/env bash
set -euo pipefail

APP_ROOT="${APP_ROOT:-/var/www/university-erp}"
RELEASE="${1:?usage: deploy.sh /absolute/path/to/release}"
CURRENT="$APP_ROOT/current"
SHARED="$APP_ROOT/shared"

test -d "$RELEASE"
test -f "$SHARED/.env"
test -d "$SHARED/storage"

ln -sfn "$SHARED/.env" "$RELEASE/.env"
rm -rf "$RELEASE/storage"
ln -sfn "$SHARED/storage" "$RELEASE/storage"

cd "$RELEASE"
composer install --no-dev --prefer-dist --no-interaction --optimize-autoloader
npm ci
npm run build
php artisan config:cache
php artisan route:cache
php artisan view:cache
php artisan migrate --force

PREVIOUS="$(readlink -f "$CURRENT" || true)"
ln -sfn "$RELEASE" "$APP_ROOT/current.next"
mv -Tf "$APP_ROOT/current.next" "$CURRENT"
php artisan queue:restart

if ! curl --fail --silent --show-error --max-time 15 "https://erp.example.edu/ready" >/dev/null; then
    if test -n "$PREVIOUS"; then
        ln -sfn "$PREVIOUS" "$APP_ROOT/current.rollback"
        mv -Tf "$APP_ROOT/current.rollback" "$CURRENT"
        "$CURRENT/artisan" queue:restart
    fi
    echo "Readiness failed; application release rolled back. Database migrations require a compatibility review." >&2
    exit 1
fi

echo "Deployment healthy: $RELEASE"
