#!/bin/sh
# Usage: run-logged.sh LOGDIR NAME [VAR=value ...] COMMAND [ARGS...]
# Runs the command with its output in LOGDIR/NAME.log. Prints one line with
# the result and the time taken; prints the whole log only when it fails, so
# parallel jobs keep their output apart. Exits with the command's status.
dir=$1
name=$2
shift 2
mkdir -p "$dir"
log=$dir/$name.log
start=$(date +%s)
env "$@" > "$log" 2>&1
rc=$?
secs=$(($(date +%s) - start))
if [ "$rc" = 0 ]; then
    printf 'ok   %-16s %3ss\n' "$name" "$secs"
else
    printf 'FAIL %-16s %3ss (exit %s), log %s:\n' "$name" "$secs" "$rc" "$log"
    cat "$log"
fi
exit "$rc"
