#!/bin/sh
# Deploys the current branch on the server. Run from the repo root:
#   npm run deploy
# Environment (NODE_ENV, PORT, PM2_APP_NAME, NEXT_PUBLIC_*, API_URL) comes from repo-root `.env`.
# First-time setup is in deploy/README.md.
set -eu

cd "$(dirname "$0")/.."

echo "==> Pulling latest code"
git pull --ff-only

echo "==> Installing dependencies"
# A full `npm ci` reinstalls every package (the slowest step). Skip it when package-lock.json
# is the same as at the last install. FORCE_INSTALL=1 npm run deploy always reinstalls.
LOCK_HASH=$(sha256sum package-lock.json | cut -d' ' -f1)
LOCK_STAMP=node_modules/.deploy-lock-hash
if [ "${FORCE_INSTALL:-0}" != 1 ] && [ -f "$LOCK_STAMP" ] && [ "$(cat "$LOCK_STAMP")" = "$LOCK_HASH" ]; then
  echo "    package-lock.json unchanged since the last install: skipping npm ci"
else
  npm ci
  echo "$LOCK_HASH" > "$LOCK_STAMP"
fi

echo "==> Building (API_URL / NEXT_PUBLIC_* from .env)"
if [ ! -f .env ]; then
  echo "Missing .env — copy .env.example and set API_URL / PORT / NEXT_PUBLIC_APP_URL" >&2
  exit 1
fi
# Make .env visible to next build in this shell (Next also reads the file itself).
set -a
# shellcheck disable=SC1091
. ./.env
set +a
echo "    API_URL=${API_URL:-<unset>}"
echo "    PORT=${PORT:-<unset>}"
# Keep Next's build cache (.next/cache) between deploys so the compile step reuses it; clear the
# rest of the old build output first.
if [ -d .next ]; then
  find .next -mindepth 1 -maxdepth 1 ! -name cache -exec rm -rf {} +
fi
npm run build

echo "==> Reloading PM2 process (passes API_URL from .env into crm-ui)"
mkdir -p logs
pm2 startOrReload deploy/ecosystem.config.cjs --update-env || pm2 start deploy/ecosystem.config.cjs --update-env
pm2 save
pm2 show crm-ui | sed -n '1,40p' || true

echo "==> Done: $(git rev-parse --short HEAD)"
