#!/usr/bin/env bash
# Pull latest code from GitHub and apply updates (run on VPS after each release)
# Usage: bash scripts/deploy/vps-update.sh
set -euo pipefail

APP_DIR="${APP_DIR:-$(cd "$(dirname "$0")/../.." && pwd)}"
BRANCH="${BRANCH:-main}"
PHP_BIN="${PHP_BIN:-php}"

cd "${APP_DIR}"

echo "== AXIS SaaS Accounting — update =="
echo "Dir: ${APP_DIR}"

if [[ ! -f .env ]]; then
  echo "ERROR: .env missing. Run vps-install.sh first or copy .env.example"
  exit 1
fi

git fetch origin "${BRANCH}"
git reset --hard "origin/${BRANCH}"

mkdir -p storage/framework/{cache,sessions,views} storage/logs bootstrap/cache
chmod -R 775 storage bootstrap/cache 2>/dev/null || true

"${PHP_BIN}" artisan down --retry=60 || true
"${PHP_BIN}" artisan storage:link || true
"${PHP_BIN}" artisan migrate --force
"${PHP_BIN}" artisan config:clear
"${PHP_BIN}" artisan route:clear
"${PHP_BIN}" artisan view:clear
"${PHP_BIN}" artisan config:cache
"${PHP_BIN}" artisan route:cache
"${PHP_BIN}" artisan view:cache
"${PHP_BIN}" artisan up

echo "== Update complete — $(git log -1 --oneline) =="
