#!/bin/sh
# Cronboard job runner. Cron calls it as:  cronboard-run <id> '<command>'
# It runs the command the way cron would, writing its output to
# $XDG_STATE_HOME/cronboard/<id>.log as it goes (so Cronboard can show it live),
# then trims that log to the last 64 KB and records the exit status in <id>.status.
# The output is printed afterwards, so cron mails it just as before.

id=$1
cmd=$2
dir=${XDG_STATE_HOME:-$HOME/.local/state}/cronboard
log=$dir/$id.log

# Recording is best effort: if it can't be set up, just run the job.
(umask 077 && mkdir -p "$dir" && : >"$log") 2>/dev/null || exec "${SHELL:-/bin/sh}" -c "$cmd"

"${SHELL:-/bin/sh}" -c "$cmd" >>"$log" 2>&1
status=$?

cat "$log"
(umask 077 && tail -c 65536 "$log" >"$dir/.$id.log.tmp") && mv -f "$dir/.$id.log.tmp" "$log"
printf '%s %s\n' "$status" "$(date +%s)" >"$dir/.$id.status.tmp" && mv -f "$dir/.$id.status.tmp" "$dir/$id.status"
exit "$status"
