#!/bin/bash
# HHPBX setup engine (root): started by hhpbx-setup.path when the wizard writes answers.json,
# or by postinst for a silent install. usage: hhpbx-setup [answers.json]
set -u
. /usr/share/hhpbx/engine/setup-steps.sh
answers=${1:-$HS_DIR/answers.json}
[ -f "$answers" ] || exit 0
install -d -m 750 -o root -g www-data "$HS_STATE"
install -d -m 700 "$HS_STATE/in"
# silent install: answers from /etc/hhpbx (root-provided, trusted paths) — copy certs to the fixed names in the root dir
if [ "$answers" != "$HS_DIR/answers.json" ]; then
	php -r '$a = json_decode(file_get_contents($argv[1]), true) ?: [];
		foreach (["pfx_path" => "cert.pfx", "pem_cert" => "cert.pem", "pem_key" => "key.pem"] as $k => $n) { if (!empty($a[$k])) copy($a[$k], $argv[2] . "/" . $n); }' "$answers" "$HS_STATE/in"
fi
trap hs_abort_if_running EXIT
hhpbx_setup_run "$answers"
