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

if [[ $EUID -ne 0 && ${OPENRESTY_GUARD_ALLOW_NON_ROOT:-0} != 1 ]]; then
  echo "OpenResty upgrade guard configuration must run as root" >&2
  exit 1
fi

script_dir=$(dirname "$(realpath "${BASH_SOURCE[0]}")")
source_script="$script_dir/prefetch-openresty-image.sh"
catalog_root=${OPENRESTY_GUARD_CATALOG_ROOT:-/opt/1panel/resource/apps/remote/openresty}
app_dir=${OPENRESTY_GUARD_APP_DIR:-/opt/1panel/apps/openresty/openresty}
libexec_dir=${OPENRESTY_GUARD_LIBEXEC_DIR:-/usr/local/libexec}
systemd_dir=${OPENRESTY_GUARD_SYSTEMD_DIR:-/etc/systemd/system}
systemctl_bin=${OPENRESTY_GUARD_SYSTEMCTL_BIN:-$(command -v systemctl || true)}

if [[ ! -d $catalog_root || ! -f $app_dir/.env ]]; then
  echo "openresty-upgrade-guard status=skipped reason=1panel-openresty-not-installed"
  exit 0
fi
if [[ ! -f $source_script ]]; then
  echo "OpenResty prefetch script not found: $source_script" >&2
  exit 1
fi
if [[ -z $systemctl_bin || ! -x $systemctl_bin ]]; then
  echo "systemctl executable not found" >&2
  exit 1
fi

install -d -m 0755 "$libexec_dir" "$systemd_dir"
install -m 0755 "$source_script" "$libexec_dir/openresty-upgrade-guard"

temporary_service=$(mktemp "${TMPDIR:-/tmp}/openresty-upgrade-guard.service.XXXXXX")
temporary_timer=$(mktemp "${TMPDIR:-/tmp}/openresty-upgrade-guard.timer.XXXXXX")
temporary_path=$(mktemp "${TMPDIR:-/tmp}/openresty-upgrade-guard.path.XXXXXX")
trap 'rm -f "$temporary_service" "$temporary_timer" "$temporary_path"' EXIT

cat >"$temporary_service" <<EOF
[Unit]
Description=Preload and validate the next 1Panel OpenResty image
After=docker.service
Wants=docker.service

[Service]
Type=oneshot
ExecStart=$libexec_dir/openresty-upgrade-guard
TimeoutStartSec=45min
Nice=10
IOSchedulingClass=idle
EOF

cat >"$temporary_timer" <<'EOF'
[Unit]
Description=Keep the next 1Panel OpenResty image ready locally

[Timer]
OnBootSec=2min
OnUnitActiveSec=6h
RandomizedDelaySec=15min
Persistent=true

[Install]
WantedBy=timers.target
EOF

cat >"$temporary_path" <<EOF
[Unit]
Description=Detect refreshed 1Panel OpenResty releases

[Path]
PathChanged=$catalog_root
Unit=openresty-upgrade-guard.service

[Install]
WantedBy=multi-user.target
EOF

install -m 0644 "$temporary_service" "$systemd_dir/openresty-upgrade-guard.service"
install -m 0644 "$temporary_timer" "$systemd_dir/openresty-upgrade-guard.timer"
install -m 0644 "$temporary_path" "$systemd_dir/openresty-upgrade-guard.path"
"$systemctl_bin" daemon-reload
"$systemctl_bin" enable --now \
  openresty-upgrade-guard.path \
  openresty-upgrade-guard.timer
"$systemctl_bin" start --no-block openresty-upgrade-guard.service

echo "openresty-upgrade-guard status=installed path=openresty-upgrade-guard.path timer=openresty-upgrade-guard.timer"
