#!/bin/bash # monsys-update — privileged installer used by the agent's auto-update flow. # # Invoked as: sudo -n /usr/local/sbin/monsys-update apply # # Lives under /usr/local/sbin (root:root 0755). The agent (running as the # `monsys` user) is allowed to call this *only* via a NOPASSWD sudoers fragment # that pins the exact command + first arg. Anything outside of that contract # is rejected. set -euo pipefail apply_one() { local target="$1"; local unit="$2"; local new="$3" if [[ -z "$new" || ! -f "$new" ]]; then echo "monsys-update: missing or non-existent path: $new" >&2; exit 2 fi if ! file -b "$new" | grep -q '^ELF '; then echo "monsys-update: not an ELF binary: $new" >&2; exit 3 fi PERM=$(stat -c '%a' "$new") if [[ "$PERM" =~ ^.[2367].$ || "$PERM" =~ ^..[2367]$ ]]; then echo "monsys-update: refusing world/group-writable file ($PERM)" >&2; exit 4 fi install -m 0755 -o root -g root "$new" "$target" rm -f "$new" || true systemctl restart --no-block "$unit" echo "monsys-update: applied $(sha256sum "$target" | awk '{print $1}') to $target" } case "${1:-}" in apply) # Backward-compatible: agent self-update. apply_one /usr/local/bin/monsys-agent monsys-agent "${2:-}" ;; apply-hub) # Hub self-update — same model, different unit. apply_one /usr/local/bin/monsys-hub monsys-hub "${2:-}" ;; version) # Diagnostic helper: print the currently-installed binary's --version. /usr/local/bin/monsys-agent --version 2>&1 || true ;; *) echo "usage: monsys-update apply # install + restart agent" >&2 echo " monsys-update apply-hub # install + restart hub" >&2 echo " monsys-update version # show agent --version" >&2 exit 2 ;; esac