#!/usr/bin/env bash
#
# sw - start a stopwatch from 0, save start time
# usage: sw [-r|--resume]
#   - start a stopwatch from the last saved start time (or current time if no last saved start time exists)
#   - "-r" stands for --resume
#
# ---
# source: https://github.com/coryfklein/sw

# shellcheck shell=bash

finish() {
  # restore cursor
  tput cnorm
  exit 0
}
trap finish EXIT

# use GNU date if possible
if command -v gdate 2>/dev/null; then
  GNU_DATE="gdate"
elif date --version 2>/dev/null | grep 'GNU coreutils' >/dev/null; then
  GNU_DATE="date"
fi

datef() {
  if [ -z "${GNU_DATE}" ]; then
    date "$@"
  else
    ${GNU_DATE} "$@"
  fi
}

# display nanoseconsd only if supported
if datef +%N | grep -q N 2>/dev/null; then
  DATE_FORMAT="+%H:%M:%S"
else
  DATE_FORMAT="+%H:%M:%S.%N"
  NANOS_SUPPORTED=true
fi

# hide cursor
tput civis

# if -r is passed, use saved start time from ~/.sw
if [ "$1" = "-r" ] || [ "$1" = "--resume" ]; then
  if [ ! -f "${HOME}/.cache/.sw" ]; then
    datef +%s >"${HOME}"/.cache/.sw
  fi
  START_TIME=$(cat "${HOME}"/.cache/.sw)
else
  START_TIME=$(datef +%s)
  printf '%s' "${START_TIME}" >"${HOME}"/.cache/.sw
fi

# GNU date accepts the input date differently than BSD
if [ -z "${GNU_DATE}" ]; then
  DATE_INPUT="-v-${START_TIME}S"
else
  DATE_INPUT="--date now-${START_TIME}sec"
fi

# shellcheck disable=SC2015,SC2312
while true; do
  STOPWATCH=$(TZ=UTC datef "${DATE_INPUT}" "${DATE_FORMAT}" \
    | ([ -n "${NANOS_SUPPORTED}" ] && sed 's/.\{7\}$//' || cat))
  printf "\r\e%s" "${STOPWATCH}"
  sleep 0.03
done
