#!/bin/sh
# Sample Background Service: a satellite's service is a program Starchaser keeps running while the satellite is on.
# It starts in this folder, with its own data folder in $STARCHASER_SATELLITE_DATA; what it prints goes to its log
# (Settings > Add-ons > Details > Show log). Turning the satellite off, safe mode, or signing out sends it TERM.
# It is meant to keep running: ending, even with exit code 0, counts as a stop, and three stops in a minute turn
# the satellite off.
heartbeat="$STARCHASER_SATELLITE_DATA/heartbeat.txt"
waiting=""
stop() {
    [ -n "$waiting" ] && kill "$waiting" 2>/dev/null
    exit 0
}
trap stop TERM INT
echo "Started; writing the time to heartbeat.txt once a minute."
while :; do
    # write a new copy, then swap it in, so a reader never sees a half-written file
    date '+%Y-%m-%d %I:%M:%S %p' > "$heartbeat.new" && mv -f "$heartbeat.new" "$heartbeat"
    sleep 60 &
    waiting=$!
    wait "$waiting"
    waiting=""
done
