#!/usr/bin/env bash
# Upgrade an existing install from a newer archive. Usage:  bash deploy/update.sh /var/www/dms
# Never touches .env or storage/. Takes the site offline for the length of the update.
set -euo pipefail
TARGET="${1:?Usage: bash deploy/update.sh /var/www/dms}"
SRC="$(cd "$(dirname "$0")/.." && pwd)"
[ -f "$TARGET/artisan" ] || { echo "$TARGET is not an install. Use deploy/install.sh first."; exit 1; }
cd "$TARGET"

echo "Backing up the database first..."; bash deploy/backup.sh "$TARGET" || { echo "Backup failed: not updating."; exit 1; }
php artisan down --retry=60 || true
trap 'php artisan up || true' EXIT

for d in app bootstrap config database public resources routes tests docs deploy; do mkdir -p "$d" && rsync -a "$SRC/$d/" "$d/"; done
composer install --no-dev --optimize-autoloader --no-interaction
npm install && npm run build
php artisan migrate --force
# Only the seeders that ADD permissions without overwriting yours. Never re-run RolePermissionSeeder or BranchSeeder here.
for s in InventoryPermissionSeeder CrmPermissionSeeder DealsPermissionSeeder ComplianceSeeder ExperienceSeeder; do php artisan db:seed --class="Database\\Seeders\\$s" --force; done
php artisan config:cache && php artisan route:cache && php artisan view:cache && php artisan event:cache
php artisan queue:restart
php artisan dms:preflight || true
echo "Updated."
