#! /usr/bin/env bash

function usage {
    cat <<EOF >&2
usage: $(basename "$0") [-q] [-T] <message>

         -q: Do not print message to standard output or standard error.
         -T: Do not include timestamp on standard error message.

EOF
    exit 1
}

function get_date {
    # Some date versions don't provide nanosecond substitution, yielding various
    # strings instead ("." on Alpine, ".3NZ" on FreeBSD). Check if we got three
    # digits and a "Z", otherwise fake the nanoseconds.
    local res
    res=$(date -u +'%Y-%m-%dT%H:%M:%S.%3NZ')

    if echo "$res" | grep -q '[0-9][0-9][0-9]Z$'; then
        echo "$res"
    else
        date -u +'%Y-%m-%dT%H:%M:%S.000Z'
    fi
}

### Main.

quiet=0
time=1

while getopts ":qT" opt; do
    case $opt in
        q)
            quiet=1
            shift
            ;;
        T)
            time=0
            shift
            ;;
        *)
            usage
            ;;
    esac
done

test $# != 0 || usage

msg="[btest] -- $*"

if [ "${quiet}" -eq 0 ]; then
    echo "${msg}"
    if [ "${time}" -eq 0 ]; then
        echo "${msg}" >&2
    else
        echo "${msg} -- $(get_date) " >&2
    fi
fi

TIME=$(python3 -c 'import time; print(int(time.time() * 1e9))')
file=$(mktemp ".progress.${TIME}.XXXXXX") || exit 1
echo "$@" >>"${file}"
