#!/usr/bin/env bash
# elphel-perfd installer - one-time, requires sudo; after this NO program
# ever needs sudo for clock control (they talk to 127.0.0.1:48890).
# Idempotent: re-running updates the script/unit and restarts the service.
# Usage:  sudo ./install.sh        (from the imagej-elphel/perfd directory)
# By Claude on 07/17/2026.
set -eu
cd "$(dirname "$0")"

if [ "$(id -u)" != 0 ]; then
    echo "elphel-perfd install needs root:  sudo $0" >&2
    exit 1
fi

echo "== installing /usr/local/lib/elphel-perfd/elphel_perfd.py"
install -D -m 0755 elphel_perfd.py /usr/local/lib/elphel-perfd/elphel_perfd.py

echo "== installing /etc/systemd/system/elphel-perfd.service"
install -m 0644 elphel-perfd.service /etc/systemd/system/elphel-perfd.service

echo "== installing /usr/local/bin/perfctl (unprivileged client)"
install -m 0755 perfctl /usr/local/bin/perfctl

echo "== systemctl daemon-reload + enable --now"
systemctl daemon-reload
systemctl enable --now elphel-perfd.service
systemctl restart elphel-perfd.service

sleep 1
echo "== status probe (unprivileged from now on):"
perfctl status || { echo "PROBE FAILED - check: journalctl -u elphel-perfd" >&2; exit 1; }
echo "== elphel-perfd installed. Try:  perfctl hold measure -- <command>"
