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

# Runs on the VPS, invoked over SSH by .github/workflows/deploy.yml.
# Pulls latest origin/main, installs PHP deps, then delegates to deploy.sh
# (which auto-detects environment from CWD containing "production" or
# "preview" and runs npm ci, npm run build, migrations, caches, queue
# restart, and the /health release-verify check).
#
# Required: DEPLOY_PATH must be set and contain "production" or "preview"
# in its path, e.g. /home/rankwiz/production/rankwiz. This is how
# deploy.sh distinguishes preview vs production deploys.
#
# Production tracks origin/main. The script will refuse to run if the
# working tree has uncommitted changes (unless FORCE_RESET=1) so that
# manual hotfixes on the VPS are never silently obliterated.

: "${DEPLOY_PATH:?DEPLOY_PATH must be set (e.g. /home/rankwiz/production/rankwiz)}"

if [[ ! -d "$DEPLOY_PATH" ]]; then
    echo "ERROR: DEPLOY_PATH does not exist: $DEPLOY_PATH" >&2
    exit 1
fi

if [[ "$DEPLOY_PATH" != *production* && "$DEPLOY_PATH" != *preview* ]]; then
    echo "ERROR: DEPLOY_PATH must contain 'production' or 'preview' for deploy.sh env detection: $DEPLOY_PATH" >&2
    exit 1
fi

cd "$DEPLOY_PATH"

# Load nvm + cPanel node, then user-local bin LAST so a compromised
# ~/bin/composer cannot shadow the real binaries.
export NVM_DIR="$HOME/.nvm"
[[ -s "$NVM_DIR/nvm.sh" ]] && source "$NVM_DIR/nvm.sh"
export PATH="/opt/cpanel/ea-nodejs22/bin:$PATH:$HOME/bin"

# Refuse to clobber uncommitted changes on the VPS.
if [[ "${FORCE_RESET:-0}" != "1" ]]; then
    if ! git diff --quiet || ! git diff --cached --quiet; then
        echo "ERROR: working tree is dirty in $DEPLOY_PATH — refusing to git reset --hard." >&2
        echo "Untracked or modified files:" >&2
        git status --short >&2
        echo "Resolve manually, or re-run with FORCE_RESET=1 to discard." >&2
        exit 1
    fi
fi

echo "==> Pulling latest origin/main into $DEPLOY_PATH"
git fetch origin main
git reset --hard origin/main

echo "==> composer install --no-dev"
composer install --no-dev --optimize-autoloader --no-interaction

# npm ci, npm run build, migrations, caches, queue:restart, and the
# /health release-verify check are all owned by deploy.sh — do not
# duplicate them here. deploy.sh auto-detects env from $PWD.
echo "==> Running deploy.sh"
bash deploy.sh

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