#!/bin/bash
# HHPBX panel worker (root). Started by hhpbx-panel.path when the page writes a job; --status writes the snapshot.
# The www-data dir is only read (cp -P, regular files only) and cleaned (rm of fixed names, never a glob or a subdir:
# www-data owns the dir and could swap any subdir for a link); all state goes to HP_OUT.
set -u
HP_IN=${HP_IN:-/var/lib/hhpbx/panel}
HP_OUT=${HP_OUT:-/var/lib/hhpbx/panel-state}
HP_BACKUPS=${HP_BACKUPS:-/var/backups/hhpbx}
HP_SHARE=${HP_SHARE:-/usr/share/hhpbx}
HP_HHPBX=${HP_HHPBX:-/usr/sbin/hhpbx}
HHPBX_MANAGE_LOG=${HHPBX_MANAGE_LOG:-/var/log/hhpbx/manage.log}
validator=$HP_SHARE/engine/hhpbx_panel_job.php

log() { printf '%s панель: %s\n' "$(date '+%F %T')" "$*" >> "$HHPBX_MANAGE_LOG" 2>/dev/null || true; }
publish() { # <name> (stdin): root-owned dir, readable by www-data; own temp name (the timer and the worker publish at once)
	local t; t=$(mktemp "$HP_OUT/.$1.XXXXXX") || return 1
	{ cat > "$t" && chmod 640 "$t" && { chown root:www-data "$t" 2>/dev/null || true; } && mv -f "$t" "$HP_OUT/$1"; } || { rm -f "$t"; return 1; }
}
jstr() { php -r 'echo json_encode($argv[1], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);' "$1"; }
take() { # <source> <dest>: a link or anything but a regular file is refused
	rm -f "$2"; [ -e "$1" ] || [ -L "$1" ] || return 0
	{ [ -f "$1" ] && [ ! -L "$1" ]; } || return 1
	timeout 600 cp -P "$1" "$2" 2>/dev/null   # timeout: swapped for a FIFO after the check
	if [ -L "$2" ] || [ ! -f "$2" ]; then rm -f "$2"; return 1; fi
	chmod 600 "$2"
}

if [ "${1:-}" = --status ]; then
	st=$("$HP_HHPBX" --json status 2>/dev/null); bl=$("$HP_HHPBX" --json backup list 2>/dev/null)
	crt=/etc/hhpbx/ssl/hhpbx.crt; [ -n "${HP_TEST:-}" ] && crt=/nonexistent
	cert=$(openssl x509 -in "$crt" -noout -subject -issuer -enddate 2>/dev/null | php -r '$r = []; foreach (file("php://stdin", FILE_IGNORE_NEW_LINES) as $l) { [$k, $v] = explode("=", $l, 2) + [1 => ""]; $r[trim($k)] = trim($v); } echo json_encode($r ?: null, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);')
	conf=/etc/hhpbx/backup.conf; key=/etc/hhpbx/backup_ed25519.pub
	php -r '$c = []; foreach (@file($argv[4], FILE_IGNORE_NEW_LINES) ?: [] as $l) { [$k, $v] = explode("=", $l, 2) + [1 => ""]; if ($k !== "") $c[$k] = $v; }
		echo json_encode(["time" => date("c"), "status" => json_decode($argv[1], true)["data"] ?? null, "status_message" => json_decode($argv[1], true)["message"] ?? "",
			"backups" => json_decode($argv[2], true)["data"] ?? [], "cert" => json_decode($argv[3], true),
			"schedule" => ["time" => $c["time"] ?? "", "keep" => $c["keep"] ?? "", "recordings" => ($c["recordings"] ?? "0") === "1"],
			"copy" => ["mode" => $c["copy"] ?? "off", "target" => $c["copy_target"] ?? ""], "sftp_key" => trim((string)@file_get_contents($argv[5]))], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);' \
		"${st:-null}" "${bl:-null}" "${cert:-null}" "$conf" "$key" | publish status.json
	find "$HP_OUT/download" -maxdepth 1 -type f -mmin +60 -delete 2>/dev/null   # a prepared download is a full copy: an hour is enough
	exit 0
fi

work=$HP_OUT/work; rm -rf "$work"; mkdir -p "$work"; chmod 700 "$work"
rm -rf "$HP_OUT/download"; install -d -m 750 "$HP_OUT/download"; chown root:www-data "$HP_OUT/download" 2>/dev/null || true
# job.json is not removed here: it was removed when taken, and one present now is the next job (PathExists starts us again)
cleanup() { rm -f "$HP_IN/archive.zip" "$HP_IN/cert.pfx" "$HP_IN/cert.pem" "$HP_IN/key.pem" 2>/dev/null; rm -rf "$work"; }
id=''; action=''
finish() { # <ok true|false> <message> [data json]
	printf '{"id":%s,"ok":%s,"message":%s,"data":%s}' "$(jstr "$id")" "$1" "$(jstr "$2")" "${3:-null}" | publish result.json
	printf '{"id":%s,"action":%s,"state":"%s","started":%s}' "$(jstr "$id")" "$(jstr "$action")" "$([ "$1" = true ] && echo done || echo failed)" "$(date +%s)" | publish progress.json
	cleanup; exit 0
}

if ! take "$HP_IN/job.json" "$work/job.json"; then log "отклонено: задание — ссылка или не файл"; rm -rf "$HP_IN/job.json"; finish false 'Недопустимый запрос'; fi
[ -f "$work/job.json" ] || exit 0
# taken: the original goes at once, so a worker killed mid-job leaves no stale job behind (the page then shows «прервалось»)
rm -f "$HP_IN/job.json"
id=$(php -r '$j = json_decode(file_get_contents($argv[1]), true); echo is_array($j) && is_string($j["id"] ?? null) && preg_match("/^[A-Za-z0-9-]{1,64}$/", $j["id"]) ? $j["id"] : "";' "$work/job.json")
action=$(php -r '$j = json_decode(file_get_contents($argv[1]), true); echo preg_replace("/[^a-z_]/", "", (string)($j["action"] ?? ""));' "$work/job.json")
for f in archive.zip cert.pfx cert.pem key.pem; do take "$HP_IN/$f" "$work/$f" || { log "отклонено: загрузка $f — ссылка или не файл"; finish false 'Недопустимый запрос'; }; done
printf '{"id":%s,"action":%s,"state":"running","started":%s}' "$(jstr "$id")" "$(jstr "$action")" "$(date +%s)" | publish progress.json

v=$(php "$validator" "$work/job.json" "$work" "$HP_BACKUPS")
if ! php -r 'exit(json_decode($argv[1], true)["ok"] ? 0 : 1);' "$v"; then log "отклонено: задание $id ($action)"; finish false 'Недопустимый запрос'; fi
kind=$(php -r 'echo json_decode($argv[1], true)["kind"];' "$v")
if [ "$kind" = download ]; then
	src=$(php -r 'echo json_decode($argv[1], true)["archive"];' "$v")
	cp "$src" "$HP_OUT/download/" && chmod 640 "$HP_OUT/download/$(basename "$src")" && { chown root:www-data "$HP_OUT/download/$(basename "$src")" 2>/dev/null || true; } &&
		finish true 'Архив готов к скачиванию' "$(jstr "$(basename "$src")")"
	finish false 'Не удалось подготовить архив'
fi
mapfile -d '' args < <(php -r 'foreach (json_decode($argv[1], true)["args"] as $a) echo $a, "\0";' "$v")
while IFS= read -r -d '' kv; do export "$kv"; done < <(php -r 'foreach (json_decode($argv[1], true)["env"] as $k => $x) echo $k, "=", $x, "\0";' "$v")
log "задание $id: $action"
out=$("$HP_HHPBX" --json "${args[@]}" 2>/dev/null)
if php -r 'exit(is_array(json_decode($argv[1], true)) ? 0 : 1);' "$out"; then
	ok=$(php -r 'echo json_decode($argv[1], true)["ok"] ? "true" : "false";' "$out")
	msg=$(php -r 'echo json_decode($argv[1], true)["message"] ?? "";' "$out")
	data=$(php -r 'echo json_encode(json_decode($argv[1], true)["data"] ?? null, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);' "$out")
	"$0" --status >/dev/null 2>&1 || true   # the page sees the new state at once
	finish "$ok" "${msg:-Готово}" "$data"
fi
finish false 'Команда завершилась без ответа, см. журнал управления'
