#!/usr/bin/env bash
# {{name}} — install/upgrade the tiny-tech fleet daemon on this box (run ON the box as the service user).
# Idempotent: node, pinned tiny-tech in ~/.tiny/daemon, the system unit. Enrolment is a separate command:
#   npx tiny-tech enroll --body {{slug}}
set -euo pipefail
TINY_TECH_VERSION="${TINY_TECH_VERSION:-{{version}}}"
HERE="$(cd "$(dirname "$0")" && pwd)"
SVC="{{slug}}-tiny"
command -v node >/dev/null || { echo "node >= 18 required (apt-get install -y nodejs npm)"; exit 1; }
mkdir -p ~/.tiny/daemon && cd ~/.tiny/daemon
printf '{"private":true,"dependencies":{"tiny-tech":"%s"}}\n' "$TINY_TECH_VERSION" > package.json
npm install --omit=dev --no-audit --no-fund --loglevel=error --ignore-scripts
[ -f "/etc/{{slug}}/env" ] || echo "!! /etc/{{slug}}/env missing (root 0600, model credentials) — the unit starts but the agent has no model until it exists" >&2
if command -v systemctl >/dev/null; then
  sed "s#__USER__#$(id -un)#g; s#__HOME__#$HOME#g" "$HERE/systemd/$SVC.service" | sudo tee "/etc/systemd/system/$SVC.service" >/dev/null
  sudo systemctl daemon-reload
  sudo systemctl enable --now "$SVC"
  sudo systemctl restart "$SVC"
  echo "node $(node -v) · tiny-tech $TINY_TECH_VERSION · $SVC $(systemctl is-active "$SVC")"
else
  echo "no systemd here — run: node ~/.tiny/daemon/node_modules/tiny-tech/dist/cli.js mesh"
fi
