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

readonly SOURCE_ROOT="/var/tmp/hlcc-deploy-src-20260726"
readonly SOURCE_COMMIT="b03619e359b9c5f5eeae73b15db6b255b9b243f7"
readonly TOOL_ROOT="/usr/local/libexec/guanghu/hlcc-candidate"
readonly PACKAGE_ROOT="/var/tmp/hlcc-offline-20260726"
readonly CONFIG_FILE="${TOOL_ROOT}/candidate-app.enterprise.ini"
readonly STATE_ROOT="/var/lib/guanghu-enterprise-code-channel"
readonly RECEIPT_ROOT="${STATE_ROOT}/receipts"
readonly RECEIPT_FILE="${RECEIPT_ROOT}/AW-GZ-001-HLCC-16.0.1.json"
readonly GUANGHU_GROUP="$(id -gn guanghu)"

if [[ "$(id -u)" != "0" ]]; then
  echo "This fixed connector must be invoked by root." >&2
  exit 2
fi

if [[ "$(git -C "${SOURCE_ROOT}" rev-parse HEAD)" != "${SOURCE_COMMIT}" ]]; then
  echo "Pinned deployment source commit does not match." >&2
  exit 3
fi

if [[ ! -d "${PACKAGE_ROOT}" || ! -f "${CONFIG_FILE}" ]]; then
  echo "Verified package staging or pinned candidate configuration is missing." >&2
  exit 3
fi

install -d -o guanghu -g "${GUANGHU_GROUP}" -m 0700 "${STATE_ROOT}"

if ss -ltnH 'sport = :3340' | grep -q .; then
  echo "Loopback candidate port 3340 is already in use." >&2
  exit 4
fi

chown -R root:"${GUANGHU_GROUP}" "${PACKAGE_ROOT}"
chmod 0750 "${PACKAGE_ROOT}"
find "${PACKAGE_ROOT}" -type f -exec chmod 0640 {} +

rollback_candidate() {
  runuser -u guanghu -- "${TOOL_ROOT}/stop-candidate.sh" || true
}
trap rollback_candidate ERR

runuser -u guanghu -- "${TOOL_ROOT}/install-candidate.sh" \
  "${PACKAGE_ROOT}" \
  "${CONFIG_FILE}"
runuser -u guanghu -- "${TOOL_ROOT}/start-candidate.sh"

install -d -o guanghu -g "${GUANGHU_GROUP}" -m 0700 "${RECEIPT_ROOT}"
runuser -u guanghu -- python3 - "${RECEIPT_FILE}" "${SOURCE_COMMIT}" <<'PY'
import json
import sys
from datetime import datetime, timezone

receipt = {
    "schema": "guanghu.agent-execution-receipt/v1",
    "agent_id": "AW-HLCC-CANDIDATE-DEPLOYER",
    "action": "deploy_release",
    "target_node_id": "AW-GZ-001",
    "release": "Forgejo 16.0.1",
    "source_commit": sys.argv[2],
    "listen": "127.0.0.1:3340",
    "scope": "isolated-candidate",
    "production_cutover": False,
    "created_at": datetime.now(timezone.utc).isoformat(),
}
with open(sys.argv[1], "w", encoding="utf-8") as handle:
    json.dump(receipt, handle, ensure_ascii=False, indent=2)
    handle.write("\n")
PY
chmod 0600 "${RECEIPT_FILE}"
trap - ERR

echo "AW-HLCC-CANDIDATE-DEPLOYER completed the registered deployment action."
