#!/usr/bin/env bash
# Install a safe automatic restart trigger for the external docs-node service.
# Run manually: sudo ./scripts/configure-docs-node-remote-auto-restart.sh [--rollback]
set -euo pipefail

repo_root=/var/www/html/dev/mcp-servers
source_file=$repo_root/docs-node/index.js
remote_unit=docs-node-remote.service
restart_unit=docs-node-remote-autorestart.service
path_unit=docs-node-remote-autorestart.path
restart_unit_file=/etc/systemd/system/$restart_unit
path_unit_file=/etc/systemd/system/$path_unit

if [[ ${1:-} == --rollback ]]; then
  sudo systemctl disable --now "$path_unit" 2>/dev/null || true
  sudo rm -f "$restart_unit_file" "$path_unit_file"
  sudo systemctl daemon-reload
  echo "Automatic docs-node restart trigger removed."
  exit 0
fi

if [[ $# -ne 0 ]]; then
  echo "Usage: $0 [--rollback]" >&2
  exit 2
fi

[[ -f $source_file ]] || { echo "docs-node source not found: $source_file" >&2; exit 1; }
sudo systemctl cat "$remote_unit" >/dev/null

sudo tee "$restart_unit_file" >/dev/null <<UNIT
[Unit]
Description=Validate and restart docs-node remote after code update
After=$remote_unit

[Service]
Type=oneshot
ExecStart=/usr/bin/node --check $source_file
ExecStart=/usr/bin/systemctl try-restart $remote_unit
UNIT

sudo tee "$path_unit_file" >/dev/null <<UNIT
[Unit]
Description=Watch docs-node remote entry point for updates

[Path]
PathChanged=$source_file
Unit=$restart_unit

[Install]
WantedBy=multi-user.target
UNIT

sudo systemctl daemon-reload
sudo systemctl enable --now "$path_unit"
sudo systemctl is-enabled "$path_unit" >/dev/null
echo "Automatic restart trigger enabled."
echo "Watched file: $source_file"
echo "A valid change restarts $remote_unit; invalid JavaScript leaves the running service untouched."
echo "Rollback: sudo $0 --rollback"
