#!/usr/bin/env bash
#
# Turista backend deploy script
#
# Run ON THE SERVER, from the Laravel app root (the folder containing `artisan`):
#
#   bash deploy.sh                     # deploy origin/dev (default)
#   bash deploy.sh main                # deploy a different branch
#   bash deploy.sh dev --maintenance   # put the app in maintenance mode during the deploy
#
# Safe to re-run. The deploy stops at the first failing step.
#
set -euo pipefail

BRANCH="dev"
MAINTENANCE="no"
for arg in "$@"; do
  case "$arg" in
    --maintenance) MAINTENANCE="yes" ;;
    *) BRANCH="$arg" ;;
  esac
done

log()  { printf '\n==> %s\n' "$*"; }
fail() { printf '\nDEPLOY FAILED: %s\n' "$*" >&2; exit 1; }

# ---------------------------------------------------------------------------
# Pre-flight checks
# ---------------------------------------------------------------------------
[ -f "artisan" ]         || fail "Run this from the Laravel app root (no 'artisan' file here)."
command -v git >/dev/null || fail "git is not available on PATH."
command -v php >/dev/null || fail "php is not available on PATH."

if command -v composer >/dev/null 2>&1; then
  COMPOSER="composer"
elif [ -f "composer.phar" ]; then
  COMPOSER="php composer.phar"
else
  fail "No composer found — neither 'composer' on PATH nor 'composer.phar' in the app root."
fi

OLD_COMMIT="$(git rev-parse --short HEAD 2>/dev/null || echo 'none')"

# ---------------------------------------------------------------------------
# Deploy steps
# ---------------------------------------------------------------------------
log "Pulling latest code (origin/${BRANCH})"
git fetch origin            || fail "git fetch failed — check network / SSH / deploy key access."
git pull --ff-only origin "${BRANCH}" \
  || fail "git pull failed — the server probably has uncommitted local edits (git status). Commit or stash them, then re-run."

log "Installing dependencies (production only)"
$COMPOSER install --no-dev --optimize-autoloader --no-interaction \
  || fail "composer install failed."

if [ "$MAINTENANCE" = "yes" ]; then
  log "Enabling maintenance mode"
  php artisan down || true
fi

log "Running database migrations"
php artisan migrate --force \
  || fail "migrations failed — check the output above; the code IS updated, but old workers still run the old code until queue:restart."

log "Clearing stale caches"
php artisan config:clear
php artisan route:clear
php artisan view:clear
php artisan event:clear

log "Restarting queue workers (they hold old code in memory until this runs; pm2 brings them back up)"
php artisan queue:restart

if [ "$MAINTENANCE" = "yes" ]; then
  log "Disabling maintenance mode"
  php artisan up
fi

NEW_COMMIT="$(git rev-parse --short HEAD)"

# ---------------------------------------------------------------------------
# Summary
# ---------------------------------------------------------------------------
log "Deploy complete: ${OLD_COMMIT} -> ${NEW_COMMIT} (origin/${BRANCH})"
echo
echo "Post-deploy checklist:"
echo "  pm2 list                              # queue worker should be 'online' (restarted just now)"
echo "  tail -n 50 storage/logs/laravel.log  # no new errors after the restart"
echo