#!/usr/bin/env bash
set -euo pipefail

NODE_BIN="${NODE_BIN:-/opt/cpanel/ea-nodejs22/bin/node}"
NPM_BIN="${NPM_BIN:-/opt/cpanel/ea-nodejs22/bin/npm}"

if [[ ! -x "$NODE_BIN" || ! -x "$NPM_BIN" ]]; then
  echo "Node.js 22 was not found at the expected cPanel path."
  echo "Set NODE_BIN and NPM_BIN, or ask the server administrator to install ea-nodejs22."
  exit 1
fi

mkdir -p tmp logs
if [[ -f package-lock.json ]]; then
  "$NPM_BIN" ci --omit=dev --no-audit --no-fund
else
  "$NPM_BIN" install --omit=dev --no-audit --no-fund
fi
"$NODE_BIN" scripts/check-env.mjs
"$NPM_BIN" run build
"$NODE_BIN" scripts/migrate.mjs
"$NODE_BIN" scripts/seed-admin.mjs
touch tmp/restart.txt

echo "YourStories deployment completed. Passenger restart requested."
