#!/usr/bin/env bash
# Persistently install the chatter-launcher systemd service ON THE DEVICE.
#
# Why this is needed: on the reMarkable Paper Pro Move, /etc and /run are
# VOLATILE overlays (upperdir on tmpfs) — units placed there are lost on reboot.
# The root partition is read-only but persistent, so we remount it rw and place
# the unit (and its enable symlink) under /usr/lib/systemd/system, which survives
# reboots. (An OS update replaces the rootfs and would require re-running this.)
#
# Uses the prebuilt dist/chatter-launcher if present, else a locally built one.
set -euo pipefail
cd "$(dirname "$0")/.."
HOST="${1:-chatter}"

LAUNCHER=dist/chatter-launcher
[ -f "$LAUNCHER" ] || LAUNCHER=tools/chatter-launcher
[ -f "$LAUNCHER" ] || { echo "launcher binary not found (dist/ or tools/) — run scripts/build.sh"; exit 1; }

scp -q "$LAUNCHER" "$HOST:/home/root/chatter/chatter-launcher"
scp -q scripts/to-chatter.sh scripts/chatter-launcher.service "$HOST:/home/root/chatter/"

ssh "$HOST" '
  set -e
  chmod +x /home/root/chatter/chatter-launcher /home/root/chatter/to-chatter.sh
  mount -o remount,rw /
  cp /home/root/chatter/chatter-launcher.service /usr/lib/systemd/system/chatter-launcher.service
  mkdir -p /usr/lib/systemd/system/multi-user.target.wants
  ln -sf ../chatter-launcher.service /usr/lib/systemd/system/multi-user.target.wants/chatter-launcher.service
  sync
  mount -o remount,ro /
  systemctl daemon-reload
  systemctl restart chatter-launcher.service
  echo "launcher: $(systemctl is-active chatter-launcher)"
'
