# Helpers for tests that need wall-clock seconds to advance between steps
# (index timestamps come from the repo directory mtime, 1 s resolution).
#
# Set TIME1S_DEBUG=1 to collect how long the barriers slept and get
# a report from time1s_report() at the end of the suite.

util__nano_now() {
    # more portable: perl -MTime::HiRes=time -e 'printf "%d\n", time()*1e9'
    date +%s%N
}

# Land this far past the second boundary: the kernel stamps inode mtimes
# from a coarse (jiffies) clock that lags CLOCK_REALTIME by up to one tick
# (~10 ms at HZ=100), so a change made right after the boundary may still
# be stamped with the previous second.
TIME1S_MARGIN_NS=${TIME1S_MARGIN_NS:-100000000}     # 100 ms

# collect/report barrier sleeping time (off by default)
TIME1S_DEBUG=${TIME1S_DEBUG:-}

# debug counters: number of barrier calls and the slept times (ns) as a
# space separated list — shell arithmetic is 32-bit in mksh, summing here
# would overflow; time1s_report() sums with awk instead
TIME1S_CALLS=0
TIME1S_SLEPT_LIST=""

# Sleep until the wall clock passes the second following $1's second
# (a nano_now timestamp), plus TIME1S_MARGIN_NS.  No-op when already there.
util__sleep_until_next_sec() {
    local t0=$1
    if [ -z "$t0" ]; then
        fail "util__sleep_until_next_sec(): missing argument"
        return 1
    fi

    local t0_s=${t0%?????????}
    local now=$(util__nano_now)
    local now_s=${now%?????????}
    local now_n=${now#$now_s}

    # d * 1e9 must not overflow 32-bit arithmetic (mksh); d < -1 means
    # long past the boundary, nothing to do
    local d=$(( t0_s - now_s + 1 ))
    [ "$d" -lt -1 ] && return 0

    # 1$now_n forces a decimal literal: bash/dash treat 0NN as octal
    local left=$(( d * 1000000000 - (1$now_n - 1000000000) + TIME1S_MARGIN_NS ))
    [ "$left" -le 0 ] && return 0

    [ -n "$TIME1S_DEBUG" ] && TIME1S_SLEPT_LIST="$TIME1S_SLEPT_LIST $left"
    sleep "$(printf '%d.%09d' $(( left / 1000000000 )) $(( left % 1000000000 )))"
}

# Barrier/stamp pair marking repo changes, so that two consecutive changes
# always land in different wall-clock seconds. Usage:
#     time1s_barrier; <modify the repo>; time1s_stamp
# The stamp must be taken *after* the change; barrier then waits out the
# stamped second, guaranteeing the next change a strictly later one.
TIME1S_LAST=""

time1s_reset() {
    TIME1S_LAST=""
}

time1s_stamp() {
    TIME1S_LAST=$(util__nano_now)
}

time1s_barrier() {
    if [ -n "$TIME1S_LAST" ]; then
        [ -n "$TIME1S_DEBUG" ] && TIME1S_CALLS=$(( TIME1S_CALLS + 1 ))
        util__sleep_until_next_sec "$TIME1S_LAST"
    fi
}

# How long the barriers slept in total vs what plain "sleep 1" would cost;
# needs TIME1S_DEBUG=1, printed by oneTimeTearDown()
time1s_report() {
    [ -n "$TIME1S_DEBUG" ] || return 0
    [ "$TIME1S_CALLS" -gt 0 ] || return 0
    echo $TIME1S_SLEPT_LIST | awk -v calls=$TIME1S_CALLS \
        '{ for (i = 1; i <= NF; i++) slept += $i }
         END { printf "time1s: %d barrier(s) slept %.3fs total (vs %d.0s of \"sleep 1\", saved %.3fs)\n", \
               calls, slept / 1e9, calls, (calls * 1e9 - slept) / 1e9 }'
}
