#!/usr/bin/env bash
# Install or update ONE client install. Run over SSH from that client's app folder:
#   cd ~/LemonLogicSoftware/Shreeji-WebApp && bash deploy/deploy.sh
# To update several clients at once use deploy/release.sh, which runs this for each of them.
# Works with a git checkout (pulls) or with files unzipped from deploy\make-release.bat (no git).
set -euo pipefail

# PHP 8.3 for the command line: Hostinger's default "php" can be an older version.
if [ -z "${PHP:-}" ]; then
  if [ -x /opt/alt/php83/usr/bin/php ]; then PHP=/opt/alt/php83/usr/bin/php; else PHP=php; fi
fi
COMPOSER=$(command -v composer2 || command -v composer || true)
APP_DIR="$(cd "$(dirname "$0")/.." && pwd)"
cd "$APP_DIR"
echo "==> Using $($PHP -r 'echo PHP_VERSION;') at $PHP"

echo "==> Folders Laravel writes to"
mkdir -p storage/framework/cache/data storage/framework/sessions storage/framework/views \
         storage/logs storage/app/private bootstrap/cache backups
chmod -R u+rwX storage bootstrap/cache backups

if [ -f .env ] && [ -d vendor ]; then
  echo "==> Maintenance mode"
  $PHP artisan down --retry=30 || true
fi

if [ -d .git ]; then
  echo "==> Pull code"
  git pull --ff-only
else
  echo "==> No git checkout: using the files already uploaded"
fi

echo "==> Composer packages"
if [ -f composer.phar ]; then
  $PHP -d memory_limit=-1 composer.phar install --no-dev --optimize-autoloader --no-interaction
else
  $PHP -d memory_limit=-1 "$COMPOSER" install --no-dev --optimize-autoloader --no-interaction
fi

if [ ! -f .env ]; then
  echo "*** No .env yet. Copy deploy/env.production.example to .env, fill it in, then run this script again."
  exit 1
fi
grep -q '^APP_KEY=base64' .env || $PHP artisan key:generate --force

echo "==> Database"
# Safety copy before changing the database (skipped on a brand-new install with no tables yet).
if $PHP artisan migrate:status >/dev/null 2>&1; then
  $PHP artisan app:backup --kind=release || echo "*** Backup before migrating failed; continuing."
fi
$PHP artisan migrate --force

echo "==> Caches"
$PHP artisan optimize:clear
$PHP artisan filament:assets
$PHP artisan optimize
$PHP artisan filament:optimize || true

echo "==> Public files"
bash deploy/sync-public.sh

echo "==> Live"
$PHP artisan up

echo "==> Smoke test"
curl -fsS "$(grep ^APP_URL .env | cut -d= -f2- | tr -d '"')/health" && echo || echo "*** Health check failed: open the site in a browser and check storage/logs."
