#!/usr/bin/env bash
# safe-job - run a command with overlap protection, timeout, logging, exit codes.
#
# Usage: safe-job [-t SECONDS] [-w WAIT_SECONDS] [-l LOCKDIR] NAME -- COMMAND [ARGS...]
#
# Exit codes:
#   0     command succeeded, OR a previous run holds the lock (logged as skipped)
#   N     the command's own exit code
#   124   command timed out (from timeout(1))
#   64    usage error
#   75    lock not acquired within -w seconds (only when -w is given)
#   130/143  interrupted by INT / TERM
set -Eeuo pipefail

timeout_s=1800
wait_s=0
lockdir="${SAFE_JOB_LOCKDIR:-/run/lock}"

usage() { sed -n '2,12p' "$0" | sed 's/^# \{0,1\}//' >&2; exit 64; }

while getopts ':t:w:l:h' o; do
    case $o in
        t) timeout_s=$OPTARG ;;
        w) wait_s=$OPTARG ;;
        l) lockdir=$OPTARG ;;
        *) usage ;;
    esac
done
shift $((OPTIND - 1))
[[ $# -ge 3 && $2 == "--" ]] || usage
NAME=$1; shift 2
[[ $NAME =~ ^[A-Za-z0-9._-]+$ ]] || { echo "safe-job: bad NAME '$NAME'" >&2; exit 64; }
[[ $timeout_s =~ ^[0-9]+$ && $wait_s =~ ^[0-9]+$ ]] || usage

log() {
    if command -v logger >/dev/null 2>&1; then
        logger -t "${NAME}[$$]" -- "$*" || true
    fi
    echo "safe-job[$NAME]: $*" >&2
}

mkdir -p "$lockdir"
exec 9>"$lockdir/${NAME}.lock"
if (( wait_s > 0 )); then
    flock -w "$wait_s" 9 || { log "could not get lock in ${wait_s}s"; exit 75; }
else
    # Skipping is not a failure: exit 0 so cron/timers do not alert on slow runs.
    flock -n 9 || { log "previous run still active, skipping"; exit 0; }
fi

WORKDIR="$(mktemp -d "${TMPDIR:-/var/tmp}/${NAME}.XXXXXX")"
export SAFE_JOB_WORKDIR=$WORKDIR
start=$SECONDS
cleanup() {
    local rc=$?
    trap - EXIT
    rm -rf -- "$WORKDIR"
    if (( rc == 0 )); then log "finished ok in $((SECONDS - start))s"
    else log "failed rc=$rc after $((SECONDS - start))s"; fi
    exit "$rc"
}
trap cleanup EXIT
on_int() { (( child )) && kill -INT "$child" 2>/dev/null; { (( child )) && wait "$child" 2>/dev/null || true; }; exit 130; }
trap on_int INT
child=0
on_term() { (( child )) && kill -TERM "$child" 2>/dev/null; { (( child )) && wait "$child" 2>/dev/null || true; }; exit 143; }
trap on_term TERM

log "starting: $* (timeout ${timeout_s}s, workdir $WORKDIR)"
# fd 9 is closed for the child so a stray background process cannot hold the lock.
# Run in background + wait so INT/TERM reach us (and the cleanup trap) immediately.
timeout --kill-after=60 "$timeout_s" "$@" 9>&- &
child=$!
wait "$child"
