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

repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
hermes_home="${LAB_HERMES_HOME:-${HOME}/.hermes}"
hermes_install="${LAB_HERMES_INSTALL_DIR:-${hermes_home}/hermes-agent}"
plugin_dir="${hermes_home}/plugins/jeannie-readonly"
source_dir="${repo_root}/infra/hermes/jeannie-readonly"
python="${hermes_install}/venv/bin/python"
cli="${hermes_install}/hermes"

[[ -x "${python}" && -f "${cli}" ]] || { echo 'Hermes installation missing; run ./jeannie deploy-hermes first.' >&2; exit 1; }
if [[ -L "${plugin_dir}" || ( -e "${plugin_dir}" && ! -f "${plugin_dir}/.jeannie-managed" ) ]]; then
    echo "Existing Hermes plugin is not Jeannie-managed: ${plugin_dir}; refusing to overwrite it." >&2
    exit 1
fi
install -d -m 0700 "${plugin_dir}"
install -m 0600 "${source_dir}/plugin.yaml" "${source_dir}/__init__.py" "${plugin_dir}/"
printf '%s\n' 'Managed by Jeannie; plugin files may be replaced on deployment.' >"${plugin_dir}/.jeannie-managed"
python3 - "${plugin_dir}/jeannie-source.json" "${repo_root}" <<'PY'
import json, os, sys, tempfile
target, repo = sys.argv[1:]
fd, tmp = tempfile.mkstemp(dir=os.path.dirname(target), prefix='.source-')
try:
    with os.fdopen(fd, 'w') as handle:
        json.dump({'repo_root': repo}, handle)
        handle.write('\n')
    os.replace(tmp, target)
finally:
    if os.path.exists(tmp):
        os.unlink(tmp)
PY

HERMES_HOME="${hermes_home}" "${python}" "${cli}" plugins enable jeannie-readonly
systemctl --user restart hermes-gateway.service
systemctl --user is-active --quiet hermes-gateway.service
echo "Hermes Jeannie read-only plugin enabled; gateway restarted. Checkout: ${repo_root}"
