#!/bin/bash
# Update continuous: git pull + composer + rebuild frontend.
# Pemakaian (di folder repo di server):
#   bash scripts/deploy/git-update.sh
#
# Opsi:
#   BRANCH=main SKIP_FRONTEND=1 bash scripts/deploy/git-update.sh

set -euo pipefail

BRANCH="${BRANCH:-main}"
SKIP_FRONTEND="${SKIP_FRONTEND:-0}"
ROOT="$(cd "$(dirname "$0")/../.." && pwd)"

if [ ! -d "$ROOT/.git" ]; then
  echo "ERROR: Bukan git repo: $ROOT"
  exit 1
fi

cd "$ROOT"

echo "==> Stash perubahan lokal (jika ada, .env tidak ikut karena di-ignore)"
git status --short

echo "==> git fetch + pull --ff-only ($BRANCH)"
git fetch origin
git checkout "$BRANCH"
if ! git pull --ff-only origin "$BRANCH"; then
  echo "ERROR: pull gagal (ada commit lokal yang bentrok)."
  echo "Simpan .env, lalu: git reset --hard origin/$BRANCH"
  exit 1
fi

echo "==> Commit: $(git rev-parse --short HEAD) — $(git log -1 --pretty=%s)"

echo "==> Update Laravel"
cd "$ROOT/api"
if [ ! -f .env ]; then
  echo "ERROR: api/.env belum ada. Jalankan git-clone-setup.sh dulu."
  exit 1
fi
if [ ! -f composer.phar ]; then
  curl -sS https://getcomposer.org/installer | php
fi
php composer.phar install --no-dev --optimize-autoloader --no-interaction
mkdir -p bootstrap/cache storage/framework/cache/data storage/framework/sessions storage/framework/views storage/logs
chmod -R 775 bootstrap/cache storage || true
php artisan config:clear || true
php artisan route:clear || true
php artisan view:clear || true
php artisan config:cache || true
php artisan route:cache || true

if [ "$SKIP_FRONTEND" = "1" ]; then
  echo "==> SKIP_FRONTEND=1 — pakai frontend/dist dari Git"
else
  echo "==> Build React SPA (Vite) di server"
  cd "$ROOT/frontend"
  if [ ! -f .env ] && [ -f .env.rumahweb.example ]; then
    cp .env.rumahweb.example .env
  fi
  for cand in \
    "$HOME/nodevenv/public_html/PADEBERKINEM/frontend/20/bin/activate" \
    "$HOME/nodevenv/public_html/PADEBERKINEM/frontend/18/bin/activate"
  do
    if [ -f "$cand" ]; then
      # shellcheck disable=SC1090
      source "$cand"
      echo "Node virtualenv: $cand"
      break
    fi
  done
  export NODE_OPTIONS="${NODE_OPTIONS:---max-old-space-size=1536}"
  npm ci || npm install
  npm run build
  echo "Hasil build: $ROOT/frontend/dist"
fi

echo "==> Sync SPA ke api/public (satu domain Laravel)"
bash "$ROOT/scripts/sync-spa-to-public.sh"

echo ""
echo "Update selesai: $(git -C "$ROOT" rev-parse --short HEAD)"
echo "Document Root → $ROOT/api/public  (frontend + API /api/*)"
echo "Tes API: curl -sS \"\${APP_URL:-https://padeberkinem.ramaboedi.com}/api/health\""
