#!/usr/bin/env bash
# Manual deploy of an Awesomate Node app WITHOUT GitHub Actions: build here,
# ship only the artefacts, install and restart on the account. Reads the same
# .awesomate.json "deploy" contract the workflow uses.
#
#   deploy-artifacts.sh <dev|staging|prod> [--path <repo-dir>] [--skip-build]
#
# It refuses to run on the hosting account itself: the account shares one
# memory ceiling across every environment and the website, and a build there
# is how deploys die with "Killed".
set -euo pipefail

ENV_NAME="${1:-}"; shift || true
DIR="$(pwd)"; SKIP_BUILD=0
while [ $# -gt 0 ]; do
  case "$1" in
    --path) DIR="$2"; shift 2 ;;
    --skip-build) SKIP_BUILD=1; shift ;;
    *) echo "unknown option $1" >&2; exit 2 ;;
  esac
done
case "$ENV_NAME" in dev|staging|prod) ;; *) echo "usage: deploy-artifacts.sh <dev|staging|prod> [--path <repo-dir>] [--skip-build]" >&2; exit 2 ;; esac
cd "$DIR"
[ -f .awesomate.json ] || { echo "✗ .awesomate.json not found in $DIR (awesomate_app_scaffold mode adopt writes it)" >&2; exit 1; }
command -v jq >/dev/null || { echo "✗ jq is required (macOS: brew install jq)" >&2; exit 1; }

if [[ "$(hostname -f 2>/dev/null || hostname)" == *awesomate.io* ]] || [[ "$HOME" == /home/* && -d /usr/local/cpanel ]]; then
  echo "✗ This looks like the hosting account. Never build on the account: run this from your own machine." >&2
  exit 1
fi

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
if ! CREDS_EVAL="$(node "$SCRIPT_DIR/resolve-account.mjs" --ssh)"; then exit 1; fi
eval "$CREDS_EVAL"
echo "→ account: $ACCT  ($U@$H)"

APP_SLUG="$(jq -r '.app_slug // empty' .awesomate.json)"; [ -n "$APP_SLUG" ] || { echo "✗ .awesomate.json has no app_slug" >&2; exit 1; }
ENV_URL="$(jq -r --arg e "$ENV_NAME" '.environments[$e].url // empty' .awesomate.json)"
BUILD_CMD="$(jq -r '.deploy.build // "npm run build"' .awesomate.json)"
INSTALL_CMD="$(jq -r '.deploy.install // "npm ci --omit=dev"' .awesomate.json)"
MIGRATE_CMD="$(jq -r '.deploy.migrate // empty' .awesomate.json)"
START_SCRIPT="$(jq -r '.deploy.start // "dist/index.js"' .awesomate.json)"
READY_PATH="$(jq -r '.deploy.ready_path // "/api/ready"' .awesomate.json)"
ARTIFACTS="$(jq -r '(.deploy.artifacts // ["dist","package.json","package-lock.json"]) | join(" ")' .awesomate.json)"
REMOTE_DIR="/home/$U/apps/${APP_SLUG}-${ENV_NAME}"
NAME="${APP_SLUG}-${ENV_NAME}"
SSH=(ssh -i "$K" -p "$P" -o StrictHostKeyChecking=accept-new "$U@$H")

if [ "$ENV_NAME" = "prod" ]; then
  read -r -p "This deploys to PRODUCTION ($ENV_URL). Type the app slug to continue: " confirm
  [ "$confirm" = "$APP_SLUG" ] || { echo "aborted"; exit 1; }
fi

if [ "$SKIP_BUILD" = 0 ]; then
  echo "→ building locally: $BUILD_CMD"
  npm ci
  bash -eo pipefail -c "$BUILD_CMD"
  case " $ARTIFACTS " in *" node_modules "*) npm prune --omit=dev ;; esac
fi
for a in $ARTIFACTS; do [ -e "$a" ] || { echo "✗ artefact '$a' does not exist after the build" >&2; exit 1; }; done

echo "→ shipping $ARTIFACTS to $REMOTE_DIR"
"${SSH[@]}" "mkdir -p '$REMOTE_DIR'"
# shellcheck disable=SC2086
tar czf - $ARTIFACTS | "${SSH[@]}" bash -lc "set -eo pipefail; cd '$REMOTE_DIR' && tar xzf - && export PATH=\"\$HOME/.npm-global/bin:/opt/cpanel/ea-nodejs22/bin:\$PATH\" && if [ -n '$INSTALL_CMD' ]; then $INSTALL_CMD; fi"
if [ -n "$MIGRATE_CMD" ]; then
  echo "→ migrating: $MIGRATE_CMD"
  "${SSH[@]}" bash -lc "set -eo pipefail; cd '$REMOTE_DIR' && export PATH=\"\$HOME/.npm-global/bin:/opt/cpanel/ea-nodejs22/bin:\$PATH\" && $MIGRATE_CMD"
fi
echo "→ restarting $NAME"
"${SSH[@]}" bash -lc "cd '$REMOTE_DIR' && printf '%s\n' '$START_SCRIPT' > .awesomate-start && (~/.npm-global/bin/pm2 restart $NAME --update-env || ~/.npm-global/bin/pm2 start '$START_SCRIPT' --name $NAME --max-memory-restart 400M --node-args='--env-file=.env') && ~/.npm-global/bin/pm2 save"

echo "→ readiness: ${ENV_URL}${READY_PATH}"
for i in 1 2 3 4 5 6; do
  sleep 5
  code="$(curl -s -o /dev/null -w '%{http_code}' "${ENV_URL}${READY_PATH}" || true)"
  if [ "$code" = "200" ]; then echo "✓ $ENV_NAME is ready at $ENV_URL"; exit 0; fi
  echo "  attempt $i: HTTP $code"
done
echo "✗ readiness failed. 503: process not listening or database unreachable; 404: no ${READY_PATH} route." >&2
exit 1
