#!/usr/bin/env bash
#
# cache - cache commands

usage() {
    printf %s "\
  $(basename "$0")
    a simple script to cache commands
    use before another command, and it will cache that commands output

  commands:
    -m, --mins    - N <minutes> to set specific cache file lifetime.

  flags:
    -h, --help    - Display this message.

  env vars:
    cache lifetime:   export CACHE_MINS=5
"
    exit 0
}

# stores cache files in /tmp, prefixed with cache.
# tmpdir=$(mktemp -d "${TMPDIR:-/tmp}"/"$(basename "$0")".XXXXXX) || return
tmpdir=$(mktemp -d "${TMPDIR:-/tmp}")
prefix=$(basename "$0")

main() {

  mins=${CACHE_MINS:-5}
  cachefile="${tmpdir}/${prefix}.$(echo "$@" | md5sum | cut -d' ' -f 1)"

  case "$1" in
    # only option is -m / --mins N to set specific cache file lifetime
    -m|--mins)
      shift
      mins=$1
      shift
      ;;
    *) usage ;;
  esac

  # if theres no cache file or its older than N mins then
  # run the command for real, cacheing the output (again).
  if [ ! -f "${cachefile}" ] \
    || test "$(find "${cachefile}" -mmin +"${mins}")"; then
    "$@" | tee "${cachefile}"
  else
    cat "${cachefile}"
  fi

}

main "$@"
