#!/usr/bin/env bash
# Install this reviewed bootstrap once as /usr/local/sbin/propertylab-map-advisor-deploy.
# Run from the confirmed app checkout; APP_DIR/APP_USER can override the site defaults.
set -Eeuo pipefail

[[ "$(id -u)" -eq 0 ]] || { echo "Run with sudo on the confirmed app server." >&2; exit 1; }
APP_DIR="${APP_DIR:-$PWD}"
APP_USER="${APP_USER:-ubuntu}"
[[ -f "$APP_DIR/artisan" && -e "$APP_DIR/.git" ]] || { echo "APP_DIR must be the confirmed production checkout." >&2; exit 1; }
command -v flock >/dev/null
exec 8>/tmp/petav3-map-advisor-bootstrap.lock
flock -n 8 || { echo "Another Map AI Advisor deploy is running." >&2; exit 1; }

GIT() { sudo -u "$APP_USER" git -C "$APP_DIR" "$@"; }
origin="$(GIT remote get-url origin)"
case "$origin" in
    https://github.com/property-lab/petav3.git|git@github.com:property-lab/petav3.git) ;;
    *) echo "Refusing to deploy an unrecognized repository." >&2; exit 1 ;;
esac
if ! GIT diff --quiet || ! GIT diff --cached --quiet; then
    echo "Commit or resolve existing server changes before deployment." >&2
    exit 1
fi
GIT fetch origin master
sha="$(GIT rev-parse FETCH_HEAD)"
bootstrap="$(mktemp /tmp/propertylab-map-advisor-deploy.XXXXXX)"
trap 'rm -f "$bootstrap"' EXIT
GIT show "$sha:scripts/deploy-update.sh" > "$bootstrap"
# Use the merged script even when the current server checkout predates the hook.
export APP_DIR APP_USER
export PROPERTYLAB_ADVISOR_INSTALL=true
export DEPLOY_EXPECTED_SHA="$sha"
bash "$bootstrap" --branch master --full-maintenance --yes
