#!/bin/bash
# FleetTruck360 — runs ON THE LIVE SERVER when you click cPanel → Git Version Control → Manage → Pull or Deploy →
# "Deploy HEAD Commit" (started by .cpanel.yml in the repository root). Every run is written to ~/fleettruck360/deploy.log.
#
#   backend/            → ~/fleettruck360/api           (keeps .env, storage/, vendor/; composer only when composer.lock changed)
#                          then: down → migrate → caches → partitions → queue restart → up
#   deploy/build/app/     → ~/app.fleettruck360.com     (ready dashboard build, made on the developer's computer)
#   deploy/build/website/ → ~/public_html               (ready website build)
#
# Optional ~/fleettruck360/deploy.conf (plain shell):  PHP=/opt/cpanel/ea-php83/root/usr/bin/php   COMPOSER=/opt/cpanel/composer/bin/composer
set -uo pipefail

REPO="$(cd "$(dirname "$0")/.." && pwd)"
BASE="$HOME/fleettruck360"
API="$BASE/api"
APP="$HOME/app.fleettruck360.com"
WEB="$HOME/public_html"
LOG="$BASE/deploy.log"
mkdir -p "$BASE" "$API" "$APP" "$WEB"
exec > >(tee -a "$LOG") 2>&1

log() { echo "[$(date '+%Y-%m-%d %H:%M:%S')] $*"; }
fail() { log "✗ $*"; exit 1; }

# shellcheck disable=SC1091
[ -f "$BASE/deploy.conf" ] && . "$BASE/deploy.conf"
PHP="${PHP:-$(command -v php || echo /usr/local/bin/php)}"
COMPOSER="${COMPOSER:-$(command -v composer || { [ -f /opt/cpanel/composer/bin/composer ] && echo /opt/cpanel/composer/bin/composer; } || echo "")}"
artisan() { (cd "$API" && "$PHP" artisan "$@"); }

log "════ deploy $(git -C "$REPO" log -1 --format='%h · %s' 2>/dev/null) ════"
command -v rsync > /dev/null || fail "rsync is not installed on this server"
"$PHP" -r 'exit(version_compare(PHP_VERSION, "8.2", ">=") ? 0 : 1);' || fail "$PHP is PHP $("$PHP" -r 'echo PHP_VERSION;') — needs 8.2+. Set PHP=… in $BASE/deploy.conf"

# ── 1. API code ───────────────────────────────────────────────────────────────────────────────────────────────────
# excluded paths are never deleted on the server (.env, uploads, logs, vendor, caches); .well-known = AutoSSL
rsync -a --delete \
  --exclude='/.env' --exclude='/.env.*' --exclude='/tests/' --exclude='/node_modules/' --exclude='/vendor/' --exclude='/storage/' \
  --exclude='/public/storage' --exclude='/public/hot' --exclude='/public/.well-known/' --exclude='/bootstrap/cache/*.php' \
  --exclude='.phpunit*' --exclude='.deployed-*' --exclude='/database/*.sqlite' \
  "$REPO/backend/" "$API/" || fail "copying the API failed"
cp "$REPO/deploy/env/api.env" "$API/.env.production.example"
mkdir -p "$API"/storage/app/private "$API"/storage/app/public "$API"/storage/framework/{cache/data,sessions,views,testing} \
  "$API"/storage/logs "$API"/bootstrap/cache
chmod -R ug+rwX "$API/storage" "$API/bootstrap/cache"
log "API code copied"

API_READY=1
if [ ! -f "$API/.env" ]; then
  API_READY=0
  log "! first deploy: $API/.env does not exist yet."
  log "  Terminal: cd $API && cp .env.production.example .env && nano .env   (deploy/README.md step 3), then click Deploy again."
fi

if [ "$API_READY" = 1 ]; then
  # composer only when composer.lock changed (or vendor/ is missing)
  LOCK_HASH="$(md5sum "$API/composer.lock" | cut -d' ' -f1)"
  if [ ! -d "$API/vendor" ] || [ "$(cat "$API/.deployed-composer" 2>/dev/null)" != "$LOCK_HASH" ]; then
    [ -n "$COMPOSER" ] || fail "composer not found — set COMPOSER=… in $BASE/deploy.conf (Terminal: which composer)"
    log "composer install (composer.lock changed)"
    (cd "$API" && "$PHP" "$COMPOSER" install --no-dev --optimize-autoloader --no-interaction --prefer-dist) || fail "composer install failed"
    echo "$LOCK_HASH" > "$API/.deployed-composer"
  fi
  if ! grep -q '^APP_KEY=base64:' "$API/.env"; then
    artisan key:generate --force || fail "key:generate failed"
  fi
  artisan down --retry=15 > /dev/null 2>&1 || true
  if artisan migrate --force; then
    artisan optimize:clear > /dev/null
    artisan config:cache && artisan route:cache && artisan view:cache
    [ -L "$API/public/storage" ] || artisan storage:link
    artisan tms:partitions
    artisan queue:restart
    artisan up
    log "API updated"
  else
    artisan up
    fail "migrate failed — the API stays on the previous database version (see the lines above)"
  fi
fi

# ── 2. Dashboard (ready build) ─────────────────────────────────────────────────────────────────────────────────────
if [ -f "$REPO/deploy/build/app/index.html" ]; then
  rsync -a --delete --exclude='.well-known/' "$REPO/deploy/build/app/" "$APP/" || fail "copying the dashboard failed"
  log "dashboard updated ($(cat "$APP/RELEASE.txt" 2>/dev/null))"
else
  log "! no dashboard build in the commit (deploy/build/app) — skipped"
fi

# ── 3. Website (ready build) ───────────────────────────────────────────────────────────────────────────────────────
# public_html may hold other things (cgi-bin, .well-known, verification files): pages are overwritten, nothing else is
# deleted — except old hashed /_astro files, which are replaced as a whole.
if [ -f "$REPO/deploy/build/website/index.html" ]; then
  rsync -a --exclude='_astro/' "$REPO/deploy/build/website/" "$WEB/" || fail "copying the website failed"
  rsync -a --delete "$REPO/deploy/build/website/_astro/" "$WEB/_astro/" || fail "copying the website assets failed"
  rm -f "$WEB/parking-page.shtml"
  log "website updated ($(cat "$WEB/RELEASE.txt" 2>/dev/null))"
else
  log "! no website build in the commit (deploy/build/website) — skipped"
fi

log "✓ deploy finished"
