#!/bin/sh
#
# chc - cache the output of a command and emit it straight from the cache
# if not expired on each run

self=chc

# check arguments for sanity
if [ "$#" -lt 3 ]; then
  printf >&2 '%s: Need a cache path, a duration, and a command\n' "${self}"
  exit 2
fi

# first argument is the cache path, second is the duration in seconds
cac="$1"
dur="$2"
shift 2

# get the current timestamp with uts(1d)
uts=$(uts) || exit

# function checks cache exists, is readable, and not expired
fresh() {
  [ -f "${cac}" ] || return
  [ -r "${cac}" ] || return
  exp=$(sed 1q -- "${cac}") || return
  [ "$((exp > uts))" -eq 1 ]
}

# write runs the command and writes it to the cache
write() {
  exp=$((uts + dur))
  printf '%u\n' "${exp}"
  "$@"
}

# if the cache isn't fresh, try to write a new one, or bail out
fresh "${cac}" || write "$@" >"${cac}" || exit

# emit the content (exclude the first line, which is the timestamp)
sed 1d -- "${cac}"
