#!/usr/bin/env bash
set -euo pipefail
[[ ${EUID} -eq 0 ]] || { echo "Run with sudo" >&2; exit 1; }
SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
PACKAGE_DIR="$(cd -- "$SCRIPT_DIR/.." && pwd)"
NODE_BIN="${SYNSONO_NODE_BIN:-$(command -v node)}"
# An update or reconcile that is running owns the release links and the updater directory: changing them now would
# make it fail its health check and roll back for no reason.
for unit in synsono-update.service synsono-reconcile.service; do
  if systemctl is-active --quiet "$unit"; then echo "A SynSono update is running ($unit); retry when it has finished" >&2; exit 1; fi
done
HOMEBRIDGE_STORAGE="${SYNSONO_HOMEBRIDGE_STORAGE:-/var/lib/homebridge}"
# Lifecycle state is SynSono-owned and lives outside the Homebridge storage directory, which Homebridge backs up as its own user.
STATE_DIR="${SYNSONO_STATE_DIR:-/var/lib/synsono/lifecycle}"
LEGACY_STATE_DIR="${SYNSONO_LEGACY_STATE_DIR:-$HOMEBRIDGE_STORAGE/synsono}"
HEALTH_DIR="${SYNSONO_HEALTH_DIR:-$HOMEBRIDGE_STORAGE/synsono-runtime}"
RELEASE_ROOT="${SYNSONO_RELEASE_ROOT:-/opt/synsono}"
CONFIG_PATH="${SYNSONO_HOMEBRIDGE_CONFIG:-$HOMEBRIDGE_STORAGE/config.json}"
PLUGIN_DIR="${SYNSONO_HOMEBRIDGE_PLUGIN_DIR:-/usr/lib/node_modules/homebridge-synsono}"
PLUGIN_PACKAGE="$PLUGIN_DIR/package.json"
MGMT_ROOT="/usr/local/lib/synsono-management"
SERVICE_USER="${SYNSONO_SERVICE_USER:-$(stat -c '%U' "$HOMEBRIDGE_STORAGE")}"
MANAGEMENT_USER="${SYNSONO_MANAGEMENT_USER:-synsono-management}"
LIFECYCLE_GROUP="${SYNSONO_LIFECYCLE_GROUP:-synsono-lifecycle}"
CURRENT_RELEASE="$(readlink -f "$RELEASE_ROOT/current")"
CURRENT_VERSION="$($NODE_BIN -p "require('$RELEASE_ROOT/current/package.json').version")"
[[ -f "$CURRENT_RELEASE/index.js" ]] || { echo "Current release entrypoint missing" >&2; exit 1; }
# Refuse to touch a broken runtime chain.
# Loading the stable loader writes a runtime health marker; as root that must never replace the marker owned by the
# running Homebridge user, so the preflight writes it to a throwaway directory instead.
PREFLIGHT_DIR="$(mktemp -d)"
trap 'rm -rf "$PREFLIGHT_DIR"' EXIT
SYNSONO_HEALTH_MARKER="$PREFLIGHT_DIR/runtime-health.json" SYNSONO_CURRENT_LINK="$RELEASE_ROOT/current" "$NODE_BIN" - "$PLUGIN_DIR/index.js" <<'NODE'
const file=process.argv[2];
delete require.cache[require.resolve(file)];
const plugin=require(file);
if(typeof plugin!=="function") throw new Error(`Preflight failed: global loader exports ${typeof plugin}`);
console.log("Preflight loader chain: function");
NODE
# Current immutable release must itself be a direct initializer, never a loader.
"$NODE_BIN" - "$CURRENT_RELEASE/index.js" <<'NODE'
const file=process.argv[2],fs=require("node:fs");
const source=fs.readFileSync(file,"utf8");
if(source.includes("SYNSONO_CURRENT_LINK")||source.includes("/opt/synsono/current")) throw new Error("Current immutable release is still a loader; refusing hotfix");
delete require.cache[require.resolve(file)];
if(typeof require(file)!=="function") throw new Error("Current immutable release does not export a function");
NODE
install -d -o root -g root -m 0755 "$MGMT_ROOT"
# The root updater lives in a versioned directory behind the "current-updater" link; this fixed path is only the
# launcher that systemd starts. From here on every accepted release brings its own updater and stable loader along,
# so this script is only needed again when the systemd units or the sudoers rule change.
SYNSONO_MANAGEMENT_ROOT="$MGMT_ROOT" SYNSONO_RELEASE_ROOT="$RELEASE_ROOT" SYNSONO_STATE_DIR="$STATE_DIR" SYNSONO_HOMEBRIDGE_PACKAGE_JSON="$PLUGIN_PACKAGE" "$NODE_BIN" "$PACKAGE_DIR/scripts/synsono-release-manager.js" install-updater "$PACKAGE_DIR"
# The launcher replaces the old updater only after the new one has been installed and has answered its self-check.
install -o root -g root -m 0755 "$PACKAGE_DIR/scripts/synsono-updater-launcher.js" "$MGMT_ROOT/release-manager.js"
# The flat updater files of earlier versions are no longer used.
for f in lifecycle-lock transaction-journal release-health manifest-signature update-check-service; do rm -f "$MGMT_ROOT/$f.js"; done
# Homebridge reads its settings surface from this stable directory: no settings form, only a pointer to the Configurator.
SETTINGS_SOURCE="$(readlink -f "$RELEASE_ROOT/current")"
if [[ -f "$SETTINGS_SOURCE/config.schema.json" && -f "$SETTINGS_SOURCE/homebridge-ui/public/index.html" ]]; then
  install -o root -g root -m 0644 "$SETTINGS_SOURCE/config.schema.json" "$PLUGIN_DIR/config.schema.json"
  install -d -o root -g root -m 0755 "$PLUGIN_DIR/homebridge-ui/public"
  install -o root -g root -m 0644 "$SETTINGS_SOURCE/homebridge-ui/public/index.html" "$PLUGIN_DIR/homebridge-ui/public/index.html"
fi
# Keep Homebridge display metadata equal to the actually active release during migration.
"$NODE_BIN" -e 'const fs=require("fs");const p=process.argv[1],v=process.argv[2],m=JSON.parse(fs.readFileSync(p,"utf8"));m.version=v;const t=p+`.tmp-${process.pid}`;fs.writeFileSync(t,JSON.stringify(m,null,2)+"\n",{mode:0o644});fs.renameSync(t,p);' "$PLUGIN_PACKAGE" "$CURRENT_VERSION"
# Normalize the shared lifecycle state contract. Homebridge owns the directory/token;
# the dedicated Management Agent gets only lifecycle-group access.
getent group "$LIFECYCLE_GROUP" >/dev/null || { echo "Missing lifecycle group: $LIFECYCLE_GROUP" >&2; exit 1; }
id "$MANAGEMENT_USER" >/dev/null 2>&1 || { echo "Missing management user: $MANAGEMENT_USER" >&2; exit 1; }
# From here on the script changes the appliance. If it stops early the Management Agent may be stopped; HomeKit control
# is unaffected, and running the script again after fixing the reported problem completes the installation.
trap 'echo "SynSono root manager hotfix did not complete. Fix the problem reported above and run this script again." >&2' ERR
# Move existing lifecycle state out of the Homebridge storage directory. The agent is stopped for the move and started
# again on its old unit when the migration refuses, so a refusal leaves the appliance as it was.
install -d -o root -g root -m 0755 "$(dirname "$STATE_DIR")"
install -d -m 0770 -o "$SERVICE_USER" -g "$LIFECYCLE_GROUP" "$STATE_DIR"
if [[ "$LEGACY_STATE_DIR" != "$STATE_DIR" && -d "$LEGACY_STATE_DIR" ]]; then
  if systemctl is-active --quiet synsono-update.service; then echo "A SynSono update is running; retry when it has finished" >&2; exit 1; fi
  AGENT_WAS_ACTIVE=0
  if systemctl is-active --quiet synsono-management-agent.service; then AGENT_WAS_ACTIVE=1; systemctl stop synsono-management-agent.service; fi
  if ! "$NODE_BIN" "$PACKAGE_DIR/scripts/migrate-lifecycle-state.js" "$LEGACY_STATE_DIR" "$STATE_DIR"; then
    [[ "$AGENT_WAS_ACTIVE" -eq 0 ]] || systemctl start synsono-management-agent.service || true
    exit 1
  fi
  # The legacy directory now holds only plugin data; it no longer needs the shared lifecycle permissions.
  chown "$SERVICE_USER:$(id -gn "$SERVICE_USER")" "$LEGACY_STATE_DIR"
  chmod 0755 "$LEGACY_STATE_DIR"
fi
chown "$SERVICE_USER:$LIFECYCLE_GROUP" "$STATE_DIR"
chmod 0770 "$STATE_DIR"
TOKEN_FILE="$STATE_DIR/management-token"
[[ -s "$TOKEN_FILE" ]] || { echo "Management token missing: $TOKEN_FILE" >&2; exit 1; }
# 15.36.5 (TD-17): owner and mode on the open file, never through a link in the state folder of the Homebridge user.
"$NODE_BIN" "$PACKAGE_DIR/scripts/synsono-own-file.js" "$TOKEN_FILE" "$(id -u "$SERVICE_USER")" "$(getent group "$LIFECYCLE_GROUP" | cut -d: -f3)" 0640
"$NODE_BIN" "$PACKAGE_DIR/scripts/synsono-own-file.js" "$STATE_DIR/update-state.json" "$(id -u "$MANAGEMENT_USER")" "$(getent group "$LIFECYCLE_GROUP" | cut -d: -f3)" 0660 >/dev/null
runuser -u "$MANAGEMENT_USER" -g "$LIFECYCLE_GROUP" -- test -x "$STATE_DIR"
runuser -u "$MANAGEMENT_USER" -g "$LIFECYCLE_GROUP" -- test -w "$STATE_DIR"
runuser -u "$MANAGEMENT_USER" -g "$LIFECYCLE_GROUP" -- test -r "$TOKEN_FILE"
[[ ! -e "$STATE_DIR/update-state.json" ]] || runuser -u "$MANAGEMENT_USER" -g "$LIFECYCLE_GROUP" -- test -w "$STATE_DIR/update-state.json"

# Replace the base Management Agent unit itself. systemd dependency directives such as
# Requires= cannot be reliably subtracted from an existing base unit with a drop-in.
rm -f /etc/systemd/system/synsono-management-agent.service.d/10-lifecycle-independence.conf
cat > /etc/systemd/system/synsono-management-agent.service <<UNIT
[Unit]
Description=SynSono Management Plane
After=network.target
[Service]
Type=simple
User=$MANAGEMENT_USER
Group=$LIFECYCLE_GROUP
WorkingDirectory=$STATE_DIR
Environment=SYNSONO_STATE_DIR=$STATE_DIR
Environment=SYNSONO_RELEASE_ROOT=$RELEASE_ROOT
Environment=SYNSONO_MANAGEMENT_TOKEN_FILE=$TOKEN_FILE
ExecStart=$NODE_BIN $MGMT_ROOT/current-agent/management-agent.js
Restart=on-failure
RestartSec=3
NoNewPrivileges=false
PrivateTmp=true
ProtectSystem=strict
ProtectHome=true
ReadWritePaths=$STATE_DIR
UMask=0077
[Install]
WantedBy=multi-user.target
UNIT

cat > /etc/systemd/system/synsono-update.service <<UNIT
[Unit]
Description=SynSono Immutable Release Update
After=network-online.target
Wants=network-online.target
# A killed, timed-out or crashed updater is reconciled immediately instead of at the next boot.
OnFailure=synsono-reconcile.service
[Service]
Type=oneshot
TimeoutStartSec=1800
User=root
Group=root
Environment=SYNSONO_STATE_DIR=$STATE_DIR
Environment=SYNSONO_RELEASE_ROOT=$RELEASE_ROOT
Environment=SYNSONO_HOMEBRIDGE_CONFIG=$CONFIG_PATH
Environment=SYNSONO_HOMEBRIDGE_PACKAGE_JSON=$PLUGIN_PACKAGE
Environment=SYNSONO_HEALTH_MARKER=$HEALTH_DIR/runtime-health.json
Environment=SYNSONO_MANAGEMENT_TOKEN_FILE=$STATE_DIR/management-token
Environment=SYNSONO_MANAGEMENT_ROOT=$MGMT_ROOT
ExecStart=$NODE_BIN $MGMT_ROOT/release-manager.js install-from-state
PrivateTmp=true
ProtectSystem=strict
ProtectHome=true
ReadWritePaths=$STATE_DIR $RELEASE_ROOT $CONFIG_PATH $PLUGIN_DIR $MGMT_ROOT $HEALTH_DIR
NoNewPrivileges=true
UMask=0022
UNIT
cat > /etc/systemd/system/synsono-reconcile.service <<UNIT
[Unit]
Description=SynSono Lifecycle Recovery
After=homebridge.service
[Service]
Type=oneshot
User=root
Group=root
Environment=SYNSONO_STATE_DIR=$STATE_DIR
Environment=SYNSONO_RELEASE_ROOT=$RELEASE_ROOT
Environment=SYNSONO_HOMEBRIDGE_CONFIG=$CONFIG_PATH
Environment=SYNSONO_HOMEBRIDGE_PACKAGE_JSON=$PLUGIN_PACKAGE
Environment=SYNSONO_HEALTH_MARKER=$HEALTH_DIR/runtime-health.json
Environment=SYNSONO_MANAGEMENT_TOKEN_FILE=$STATE_DIR/management-token
Environment=SYNSONO_MANAGEMENT_ROOT=$MGMT_ROOT
ExecStart=$NODE_BIN $MGMT_ROOT/release-manager.js reconcile
PrivateTmp=true
ProtectSystem=strict
ProtectHome=true
ReadWritePaths=$STATE_DIR $RELEASE_ROOT $CONFIG_PATH $PLUGIN_DIR $MGMT_ROOT $HEALTH_DIR
NoNewPrivileges=true
[Install]
WantedBy=multi-user.target
UNIT
cat > /etc/systemd/system/synsono-restart.service <<UNIT
[Unit]
Description=SynSono Runtime Restart
[Service]
Type=oneshot
User=root
Group=root
Environment=SYNSONO_STATE_DIR=$STATE_DIR
Environment=SYNSONO_RELEASE_ROOT=$RELEASE_ROOT
Environment=SYNSONO_HEALTH_MARKER=$HEALTH_DIR/runtime-health.json
ExecStart=$NODE_BIN $MGMT_ROOT/release-manager.js restart-runtime
TimeoutStartSec=60
PrivateTmp=true
ProtectSystem=strict
ProtectHome=true
ReadWritePaths=$STATE_DIR
NoNewPrivileges=true
UNIT
# The Management Agent runs exactly this systemctl (scripts/synsono-management-plane.js); the sudo rule names the same
# path, or sudo would not match it (15.3.4).
SYSTEMCTL=/usr/bin/systemctl
[[ -x "$SYSTEMCTL" ]] || { echo "SynSono needs $SYSTEMCTL" >&2; exit 1; }
command -v visudo >/dev/null || { echo "SynSono needs visudo (package sudo) to check its sudo rule" >&2; exit 1; }
# The rule is written and checked under a name sudo ignores (it contains a dot) and only then put in place: a broken file
# in /etc/sudoers.d would stop sudo for the whole system (15.3.4, code review R1).
SUDOERS_TMP="$(mktemp /etc/sudoers.d/.synsono-management-agent.XXXXXX)"
# The Management Agent's only elevation routes: starting the fixed updater unit and the fixed runtime-restart unit.
printf '%s ALL=(root) NOPASSWD: %s start synsono-update.service\n%s ALL=(root) NOPASSWD: %s start --no-block synsono-restart.service\n' "$MANAGEMENT_USER" "$SYSTEMCTL" "$MANAGEMENT_USER" "$SYSTEMCTL" > "$SUDOERS_TMP"
chmod 0440 "$SUDOERS_TMP"
visudo -cf "$SUDOERS_TMP" >/dev/null || { rm -f "$SUDOERS_TMP"; echo "SynSono sudo rule failed visudo -cf; nothing was installed in /etc/sudoers.d" >&2; exit 1; }
mv -f "$SUDOERS_TMP" /etc/sudoers.d/synsono-management-agent
systemctl daemon-reload
# Record which revision of the root infrastructure (units, sudoers rule, launcher) this run installed.
# 15.10.0: the infrastructure revisions after the first (infra/apply-<n>.sh), in order. A failure stops the installer
# before the revision is recorded; on a device that is no SynSono Box they change nothing.
while IFS= read -r infra_script; do
  SYNSONO_NODE_BIN="$NODE_BIN" SYNSONO_STATE_DIR="$STATE_DIR" SYNSONO_RELEASE_ROOT="$RELEASE_ROOT" SYNSONO_HOMEBRIDGE_CONFIG="$CONFIG_PATH" SYNSONO_HOMEBRIDGE_PACKAGE_JSON="$PLUGIN_PACKAGE" SYNSONO_HEALTH_MARKER="$HEALTH_DIR/runtime-health.json" SYNSONO_MANAGEMENT_TOKEN_FILE="$TOKEN_FILE" SYNSONO_MANAGEMENT_ROOT="$MGMT_ROOT" SYNSONO_MANAGEMENT_USER="$MANAGEMENT_USER" bash "$infra_script"
done < <(find "$PACKAGE_DIR/infra" -maxdepth 1 -name 'apply-*.sh' 2>/dev/null | sort -V)
SYNSONO_MANAGEMENT_ROOT="$MGMT_ROOT" SYNSONO_RELEASE_ROOT="$RELEASE_ROOT" SYNSONO_STATE_DIR="$STATE_DIR" "$NODE_BIN" "$PACKAGE_DIR/scripts/synsono-release-manager.js" record-infrastructure "$PACKAGE_DIR" >/dev/null
# Verify the effective dependency graph, not merely the unit-file text.
AGENT_REQUIRES="$(systemctl show synsono-management-agent.service --property=Requires --value)"
AGENT_AFTER="$(systemctl show synsono-management-agent.service --property=After --value)"
[[ " $AGENT_REQUIRES " != *" synsono-reconcile.service "* ]] || { echo "Invalid Management Agent dependency: Requires=synsono-reconcile.service" >&2; exit 1; }
[[ " $AGENT_AFTER " != *" synsono-reconcile.service "* ]] || { echo "Invalid Management Agent dependency: After=synsono-reconcile.service" >&2; exit 1; }
systemctl restart synsono-management-agent.service
# Bounded authenticated readiness check; systemctl active alone is not sufficient.
"$NODE_BIN" - "$TOKEN_FILE" <<'NODE'
"use strict";
const fs=require("node:fs"),http=require("node:http");
const token=fs.readFileSync(process.argv[2],"utf8").trim(),deadline=Date.now()+15000;
function probe(){
 const req=http.get({hostname:"127.0.0.1",port:8788,path:"/v2/health",headers:{authorization:"Bearer "+token},timeout:1500},res=>{
  let body="";res.on("data",c=>body+=c);res.on("end",()=>{try{const j=JSON.parse(body);if(res.statusCode===200&&j.ok===true)return process.exit(0)}catch{};retry()});
 });
 req.on("timeout",()=>req.destroy());req.on("error",retry);
}
function retry(){if(Date.now()>=deadline){console.error("Management Agent authenticated health check timed out");process.exit(1)}setTimeout(probe,250)}
probe();
NODE
# Postflight: no release pointer change, no agent switch, loader still resolves to a function.
[[ "$(readlink -f "$RELEASE_ROOT/current")" == "$CURRENT_RELEASE" ]] || { echo "Current release changed unexpectedly" >&2; exit 1; }
echo "Management Agent bundle left unchanged: $(readlink -f "$MGMT_ROOT/current-agent")"
SYNSONO_HEALTH_MARKER="$PREFLIGHT_DIR/runtime-health.json" SYNSONO_CURRENT_LINK="$RELEASE_ROOT/current" "$NODE_BIN" - "$PLUGIN_DIR/index.js" <<'NODE'
const file=process.argv[2]; delete require.cache[require.resolve(file)]; if(typeof require(file)!=="function") process.exit(1);
NODE
echo "SynSono root manager hotfix installed. Active application remains $CURRENT_VERSION at $CURRENT_RELEASE"
