#!/usr/bin/env bash
set -euo pipefail
if [[ ${EUID} -ne 0 ]]; then echo "Run with sudo: sudo npm run appliance:bootstrap" >&2; exit 1; fi
SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
PACKAGE_DIR="$(cd -- "${SCRIPT_DIR}/.." && pwd)"
NODE_BIN="${SYNSONO_NODE_BIN:-$(command -v node)}"
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}"
HOMEBRIDGE_PLUGIN_DIR="${SYNSONO_HOMEBRIDGE_PLUGIN_DIR:-/usr/lib/node_modules/homebridge-synsono}"
HOMEBRIDGE_PACKAGE_JSON="$HOMEBRIDGE_PLUGIN_DIR/package.json"
SERVICE_USER="${SYNSONO_SERVICE_USER:-}"
if [[ -z "$SERVICE_USER" ]]; then SERVICE_USER="$(systemctl show homebridge.service --property=User --value 2>/dev/null || true)"; fi
if [[ -z "$SERVICE_USER" || "$SERVICE_USER" == root ]]; then SERVICE_USER="$(stat -c '%U' "$HOMEBRIDGE_STORAGE" 2>/dev/null || true)"; fi
if [[ -z "$SERVICE_USER" || "$SERVICE_USER" == root ]]; then SERVICE_USER="${SUDO_USER:-}"; fi
[[ -n "$SERVICE_USER" && "$SERVICE_USER" != root ]] || { echo "Could not detect Homebridge service user" >&2; exit 1; }
SERVICE_GROUP="${SYNSONO_SERVICE_GROUP:-$(id -gn "$SERVICE_USER")}"
MANAGEMENT_USER="${SYNSONO_MANAGEMENT_USER:-synsono-management}"
LIFECYCLE_GROUP="${SYNSONO_LIFECYCLE_GROUP:-synsono-lifecycle}"
TRUST_KEY_SOURCE="${SYNSONO_UPDATE_PUBLIC_KEY_SOURCE:-$PACKAGE_DIR/config/synsono-update-public.pem}"
[[ -x "$NODE_BIN" ]] || { echo "Node.js executable unavailable: $NODE_BIN" >&2; exit 1; }
# 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
# Moves existing lifecycle state out of the Homebridge storage directory. The agent is stopped for the move and is
# started again on its old unit when the migration refuses, so a refusal leaves the appliance as it was.
migrate_lifecycle_state() {
  [[ "$LEGACY_STATE_DIR" != "$STATE_DIR" && -d "$LEGACY_STATE_DIR" ]] || return 0
  if systemctl is-active --quiet synsono-update.service; then echo "A SynSono update is running; retry when it has finished" >&2; exit 1; fi
  local 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"
}
for command in systemctl getent groupadd useradd usermod install runuser; do
  command -v "$command" >/dev/null || { echo "Required command unavailable: $command" >&2; exit 1; }
done
[[ -s "$TRUST_KEY_SOURCE" ]] || { echo "Trusted update public key unavailable: $TRUST_KEY_SOURCE" >&2; exit 1; }
"$NODE_BIN" -e 'const fs=require("node:fs"),crypto=require("node:crypto");const key=crypto.createPublicKey(fs.readFileSync(process.argv[1]));if(key.asymmetricKeyType!=="ed25519")throw new Error(`Expected Ed25519 public key, got ${key.asymmetricKeyType}`);' "$TRUST_KEY_SOURCE"
getent group "$LIFECYCLE_GROUP" >/dev/null || groupadd --system "$LIFECYCLE_GROUP"
id "$MANAGEMENT_USER" >/dev/null 2>&1 || useradd --system --home-dir "$STATE_DIR" --no-create-home --shell /usr/sbin/nologin --gid "$LIFECYCLE_GROUP" "$MANAGEMENT_USER"
usermod -a -G "$LIFECYCLE_GROUP" "$SERVICE_USER"
install -d -m 0755 /usr/local/lib/synsono-management
install -d -m 0755 /usr/local/lib/synsono-management/agents
install -d -o root -g root -m 0755 /etc/synsono
install -o root -g root -m 0644 "$TRUST_KEY_SOURCE" /etc/synsono/update-signing-key.pem
install -d -m 0755 "$RELEASE_ROOT" "$RELEASE_ROOT/releases"
install -d -o root -g root -m 0755 "$(dirname "$STATE_DIR")"
install -d -m 0770 -o "$SERVICE_USER" -g "$LIFECYCLE_GROUP" "$STATE_DIR"
migrate_lifecycle_state
install -d -m 0750 -o "$SERVICE_USER" -g "$SERVICE_GROUP" "$HEALTH_DIR"
# Bootstrap immutable release before installing the fixed loader.
if [[ -L "$RELEASE_ROOT/current" && -e "$RELEASE_ROOT/current/package.json" ]]; then
  echo "Existing immutable SynSono release preserved: $(readlink -f "$RELEASE_ROOT/current")"
else
  SYNSONO_RELEASE_ROOT="$RELEASE_ROOT" SYNSONO_STATE_DIR="$STATE_DIR" "$NODE_BIN" "$PACKAGE_DIR/scripts/synsono-release-manager.js" bootstrap "$PACKAGE_DIR"
fi
# 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.
install -d -o root -g root -m 0755 /usr/local/lib/synsono-management
# The plugin directory and its metadata must exist before the updater and the loader are installed into them.
install -d -o root -g root -m 0755 "$HOMEBRIDGE_PLUGIN_DIR"
SYNSONO_MANAGEMENT_ROOT=/usr/local/lib/synsono-management SYNSONO_RELEASE_ROOT="$RELEASE_ROOT" SYNSONO_STATE_DIR="$STATE_DIR" SYNSONO_HOMEBRIDGE_PACKAGE_JSON="$HOMEBRIDGE_PACKAGE_JSON" "$NODE_BIN" "$PACKAGE_DIR/scripts/synsono-release-manager.js" install-updater "$PACKAGE_DIR"
# The launcher is put in place only after the updater has been installed and has answered its self-check.
install -o root -g root -m 0755 "$PACKAGE_DIR/scripts/synsono-updater-launcher.js" /usr/local/lib/synsono-management/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 "/usr/local/lib/synsono-management/$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" "$HOMEBRIDGE_PLUGIN_DIR/config.schema.json"
  install -d -o root -g root -m 0755 "$HOMEBRIDGE_PLUGIN_DIR/homebridge-ui/public"
  install -o root -g root -m 0644 "$SETTINGS_SOURCE/homebridge-ui/public/index.html" "$HOMEBRIDGE_PLUGIN_DIR/homebridge-ui/public/index.html"
fi
ACTIVE_VERSION="$("$NODE_BIN" -p "require('${RELEASE_ROOT}/current/package.json').version")"
$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);' "$HOMEBRIDGE_PACKAGE_JSON" "$ACTIVE_VERSION"
# Management agent is deliberately installed outside the replaceable release tree.
# Agent bundles are versioned so OTA can atomically switch and roll back the management plane.
AGENT_SOURCE_DIR="$(readlink -f "$RELEASE_ROOT/current")"
# The Management Plane carries its own version when the release declares one; otherwise it follows the release version.
PLANE_METADATA="$AGENT_SOURCE_DIR/src/management/management-plane.json"
PLANE_VERSION="$ACTIVE_VERSION"
if [[ -f "$PLANE_METADATA" ]]; then PLANE_VERSION="$("$NODE_BIN" -p "require('$PLANE_METADATA').version")"; fi
[[ "$PLANE_VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+([-.][0-9A-Za-z.-]+)?$ ]] || { echo "Invalid Management Plane version: $PLANE_VERSION" >&2; exit 1; }
AGENT_BUNDLE_DIR="/usr/local/lib/synsono-management/agents/$PLANE_VERSION"
install -d -o root -g root -m 0755 "$AGENT_BUNDLE_DIR"
install -o root -g root -m 0644 "$AGENT_SOURCE_DIR/src/management/update-check-service.js" "$AGENT_BUNDLE_DIR/update-check-service.js"
install -o root -g root -m 0644 "$AGENT_SOURCE_DIR/src/management/manifest-signature.js" "$AGENT_BUNDLE_DIR/manifest-signature.js"
install -o root -g root -m 0644 "$AGENT_SOURCE_DIR/src/management/transaction-journal.js" "$AGENT_BUNDLE_DIR/transaction-journal.js"
install -o root -g root -m 0644 "$AGENT_SOURCE_DIR/src/management/maintenance-status.js" "$AGENT_BUNDLE_DIR/maintenance-status.js"
install -o root -g root -m 0644 "$AGENT_SOURCE_DIR/scripts/synsono-management-plane.js" "$AGENT_BUNDLE_DIR/management-agent.js"
if [[ -f "$PLANE_METADATA" ]]; then install -o root -g root -m 0644 "$PLANE_METADATA" "$AGENT_BUNDLE_DIR/management-plane.json"; fi
if [[ -f "$AGENT_SOURCE_DIR/config/synsono-update-keys.json" ]]; then install -o root -g root -m 0644 "$AGENT_SOURCE_DIR/config/synsono-update-keys.json" "$AGENT_BUNDLE_DIR/update-keys.json"; fi
ln -sfn "$AGENT_BUNDLE_DIR" /usr/local/lib/synsono-management/.current-agent.new
mv -Tf /usr/local/lib/synsono-management/.current-agent.new /usr/local/lib/synsono-management/current-agent
TOKEN_FILE="$STATE_DIR/management-token"
# The umask applies only to the token: set in the script itself it made every file written afterwards root-only,
# including infrastructure.json, which the Configurator then could not read.
# 15.36.5 (TD-17): the state folder belongs to the Homebridge user; the token is made and owned on the open file, never
# through a link in its place (scripts/synsono-own-file.js).
"$NODE_BIN" "$PACKAGE_DIR/scripts/synsono-own-file.js" "$TOKEN_FILE" "$(id -u "$SERVICE_USER")" "$(getent group "$LIFECYCLE_GROUP" | cut -d: -f3)" 0640 --create-token
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 /usr/local/lib/synsono-management/current-agent/management-agent.js
Restart=on-failure
RestartSec=3
# The agent uses a single NOPASSWD sudoers command to start the fixed root updater.
# A setuid transition is impossible when NoNewPrivileges is enabled.
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=$HOMEBRIDGE_PACKAGE_JSON
Environment=SYNSONO_HEALTH_MARKER=$HEALTH_DIR/runtime-health.json
Environment=SYNSONO_MANAGEMENT_TOKEN_FILE=$TOKEN_FILE
Environment=SYNSONO_MANAGEMENT_ROOT=/usr/local/lib/synsono-management
ExecStart=$NODE_BIN /usr/local/lib/synsono-management/release-manager.js install-from-state
PrivateTmp=true
ProtectSystem=strict
ProtectHome=true
ReadWritePaths=$STATE_DIR $RELEASE_ROOT $CONFIG_PATH $HOMEBRIDGE_PLUGIN_DIR /usr/local/lib/synsono-management
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=$HOMEBRIDGE_PACKAGE_JSON
Environment=SYNSONO_HEALTH_MARKER=$HEALTH_DIR/runtime-health.json
Environment=SYNSONO_MANAGEMENT_TOKEN_FILE=$TOKEN_FILE
Environment=SYNSONO_MANAGEMENT_ROOT=/usr/local/lib/synsono-management
ExecStart=$NODE_BIN /usr/local/lib/synsono-management/release-manager.js reconcile
PrivateTmp=true
ProtectSystem=strict
ProtectHome=true
ReadWritePaths=$STATE_DIR $RELEASE_ROOT $CONFIG_PATH $HOMEBRIDGE_PLUGIN_DIR /usr/local/lib/synsono-management $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 /usr/local/lib/synsono-management/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
"$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
# Validate the effective least-privilege state contract before restarting the agent.
runuser -u "$MANAGEMENT_USER" -g "$LIFECYCLE_GROUP" -- test -x "$STATE_DIR"
runuser -u "$MANAGEMENT_USER" -g "$LIFECYCLE_GROUP" -- test -r "$TOKEN_FILE"
runuser -u "$MANAGEMENT_USER" -g "$LIFECYCLE_GROUP" -- test -w "$STATE_DIR"
[[ ! -e "$STATE_DIR/update-state.json" ]] || runuser -u "$MANAGEMENT_USER" -g "$LIFECYCLE_GROUP" -- test -w "$STATE_DIR/update-state.json"
systemctl daemon-reload
# Record which revision of the root infrastructure (units, sudoers rule, launcher) this run installed, so a release
# that needs a newer one can say so in the Configurator.
# 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="$HOMEBRIDGE_PACKAGE_JSON" SYNSONO_HEALTH_MARKER="$HEALTH_DIR/runtime-health.json" SYNSONO_MANAGEMENT_TOKEN_FILE="$TOKEN_FILE" SYNSONO_MANAGEMENT_ROOT="/usr/local/lib/synsono-management" 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=/usr/local/lib/synsono-management 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
# The Management Agent must remain restartable during an active lifecycle transaction.
# Reconcile is boot/recovery work and must never be a hard or ordering dependency here.
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 enable synsono-management-agent.service >/dev/null
systemctl enable synsono-reconcile.service >/dev/null
systemctl restart synsono-management-agent.service
systemctl is-active --quiet synsono-management-agent.service || { echo "Management Agent failed to start" >&2; exit 1; }
[[ "$(systemctl show synsono-management-agent.service --property=NoNewPrivileges --value)" == "no" ]] || { echo "Management Agent cannot launch the privileged updater: NoNewPrivileges must be disabled" >&2; exit 1; }
"$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();
let attempts=0;
function check(){
  attempts++;
  const request=http.get({hostname:"127.0.0.1",port:8788,path:"/v2/health",headers:{authorization:`Bearer ${token}`}},response=>{
    let body=""; response.setEncoding("utf8"); response.on("data",chunk=>body+=chunk);
    response.on("end",()=>{
      try{const value=JSON.parse(body);if(response.statusCode===200&&value.ok===true){console.log(`Management Agent ${value.agentVersion} health check passed.`);return}}
      catch{}
      retry(`HTTP ${response.statusCode}: ${body}`);
    });
  });
  request.setTimeout(1000,()=>request.destroy(new Error("timeout")));
  request.on("error",error=>retry(error.message));
}
function retry(reason){if(attempts>=20){console.error(`Management Agent health check failed: ${reason}`);process.exit(1)}setTimeout(check,250)}
check();
NODE
echo "SynSono appliance bootstrap installed."
echo "Active release: $(readlink -f "$RELEASE_ROOT/current")"
echo "Management plane: /usr/local/lib/synsono-management"
