#!/bin/sh
# Package compatibility and explicit maintenance; normal CLI and init run the installed binary directly.
[ -z "${IPKG_INSTROOT:-}" ] || exit 0
bin=/usr/sbin/changeguard_bin
config=/etc/changeguard/config.json
warn() { printf '%s\n' "changeguard: $*" >&2; }
case "${1:-}" in
 runtime-path) printf '%s\n' "$bin" ;;
 run) shift; exec "$bin" "$@" ;;
 preinst) /etc/init.d/changeguard stop || warn 'service stop needs attention' ;;
 prerm)
  /etc/init.d/changeguard stop || warn 'service stop needs attention'
  /etc/init.d/changeguard disable || warn 'service disable needs attention'
 ;;
 postinst)
  "$bin" initialize --config "$config" >/dev/null || warn 'initial configuration needs attention'
  # One-time old-layout conversion is independent of service availability.
  # Failure leaves the old configuration intact; the daemon starts in diagnostic mode.
  "$bin" migrate-control --config "$config" >/dev/null || warn 'legacy control state migration needs attention'
  /etc/init.d/changeguard enable || warn 'service enable needs attention'
  /etc/init.d/changeguard restart || warn 'service restart needs attention'
 ;;
 repair-config)
  /usr/libexec/changeguard-config-repair "$config" || exit 1
  "$bin" migrate-control --config "$config" || exit 1
 ;;
 *) exit 2 ;;
esac
exit 0
