#!/usr/bin/env bash
# Checks 2, 3, 6, 7, 8 and 9 of the card, on Linux. Checks 4 and 5 are test/e2e.sh.
# Every run has its own ledger in a temporary folder, and check 8 replaces the sleep and lock
# programs with stubs, so this never suspends the machine it runs on. Check 9 takes about two minutes.
set -u
cd "$(dirname "$0")/.."
tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT
mkdir -p out
fails=0
check() { if [ "$1" = "$2" ]; then echo "ok    $3"; else echo "FAIL  $3: got [$1] want [$2]"; fails=$((fails + 1)); fi; }
has() { if grep -qxF -e "$2" "$1"; then echo "ok    $3"; else echo "FAIL  $3: no line [$2] in:"; sed 's/^/      /' "$1"; fails=$((fails + 1)); fi; }

echo "== 2. build and hygiene"
GOFLAGS=-mod=mod GOPROXY=off go build -o bedtime . && echo "ok    go build offline" || { echo "FAIL  go build"; fails=$((fails + 1)); }
check "$(go vet ./... 2>&1)" "" "go vet clean"
check "$(gofmt -l .)" "" "gofmt -l prints nothing"
check "$(grep -c require go.mod)" 0 "go.mod has no require"
check "$(go list -deps -f '{{if not .Standard}}{{.ImportPath}}{{end}}' ./... | grep -v '^bedtime$')" "" "only standard library packages"
dash=$(printf '\xe2\x80\x94')
check "$(grep -rlF "$dash" --exclude-dir=.git . | grep -v '^./bedtime$')" "" "no file contains an em dash"

echo "== 3. dry run, fresh"
L3="$tmp/c3/none.tsv"
t0=$(date +%s%N)
BEDTIME_LEDGER="$L3" ./bedtime 23:00 --dry-run --clock-start 2026-10-13T21:00:00 > "$tmp/dry"; rc=$?
t1=$(date +%s%N)
sed "s#^Ledger: .*#Ledger: <temporary file>#" "$tmp/dry" > out/dry-run.txt
check "$rc" 0 "exit 0"
check "$([ $(((t1 - t0) / 1000000)) -lt 1000 ] && echo yes)" yes "finished in $(((t1 - t0) / 1000000)) ms"
check "$(test -e "$L3" || test -e "$tmp/c3" || echo none)" none "no ledger file created"
check "$(sed -n 2p "$tmp/dry")" "Schedule of extensions, night of Tue 2026-10-13." "heading is line 2"
check "$(sed -E 's/\((systemctl|loginctl) (not found|found)\)/(<program> found)/g; s#^Ledger: '"$L3"'$#Ledger: <path>#' "$tmp/dry")" "$(cat <<'X'
Clock: simulated from 2026-10-13T21:00:00 at 1x.
Schedule of extensions, night of Tue 2026-10-13.
Bedtime is 23:00 on Tue 2026-10-13.
Asking for five more minutes opens at 22:59:00, one minute before.
Each grant is half the one before. The first grant is 15 minutes.
The most that can ever be granted in total is 30 minutes.

1. Granted 15 minutes. Remaining that can ever be granted: 15 minutes.
   Bedtime is now 23:15:00.
2. Granted 7 minutes 30 seconds. Remaining that can ever be granted: 7 minutes 30 seconds.
   Bedtime is now 23:22:30.
3. Granted 3 minutes 45 seconds. Remaining that can ever be granted: 3 minutes 45 seconds.
   Bedtime is now 23:26:15.
4. Granted 1 minute 52.5 seconds. Remaining that can ever be granted: 1 minute 52.5 seconds.
   Bedtime is now 23:28:07.5.
5. Granted 56.25 seconds. Remaining that can ever be granted: 56.25 seconds.
   Bedtime is now 23:29:03.75.
6. Granted 28.125 seconds. Remaining that can ever be granted: 28.125 seconds.
   Bedtime is now 23:29:31.875.
7. Granted 14.062 seconds. Remaining that can ever be granted: 14.063 seconds.
   Bedtime is now 23:29:45.937.
No grant 8: it would be 7.031 seconds, under the 10 second minimum.
The last possible bedtime is 23:29:45.937.
Halving rounds down to the millisecond. 11 milliseconds of the 30 minutes can never be granted.

Action: suspend (<program> found). If that fails: lock (<program> found). If that fails: print and exit 3.
Ledger: <path>
Nothing was waited for, written or done.
X
)" "output equals the card's schedule line for line"

echo "== 6. the wall holds across restarts"
L6="$tmp/l6.tsv"
mkfifo "$tmp/in6"
t0=$(date +%s%N)
BEDTIME_LEDGER="$L6" ./bedtime 23:00 --clock-start 2026-10-13T22:58:00 --clock-speed 60 < "$tmp/in6" > "$tmp/o6" &
pid=$!
exec 3> "$tmp/in6"
until grep -q '^Asking is open' "$tmp/o6"; do sleep 0.01; done
sleep 0.05; echo "five more minutes" >&3
while [ $((($(date +%s%N) - t0) / 1000000)) -lt 3000 ]; do sleep 0.01; done
kill -INT "$pid"; wait "$pid"; rc=$?; exec 3>&-
cp "$tmp/o6" out/restart-1-interrupted.txt
check "$rc" 130 "SIGINT exits 130"
check "$(tail -n 1 "$tmp/o6")" "Stopped. Nothing was done." "SIGINT output ends Stopped"
has "$tmp/o6" "Granted 15 minutes. Remaining that can ever be granted: 15 minutes." "the one request was granted"
check "$(tail -n 1 "$L6" | cut -f4,5)" "$(printf 'end\taction=interrupted')" "ledger end action=interrupted"
BEDTIME_LEDGER="$tmp/l6b.tsv" ./bedtime 23:00 --clock-start 2026-10-13T22:58:00 --clock-speed 60 < /dev/null > "$tmp/o6b" &
pid=$!; sleep 1; kill -TERM "$pid"; wait "$pid"; rc=$?
check "$rc" 143 "SIGTERM exits 143"
check "$(tail -n 1 "$tmp/o6b")" "Stopped. Nothing was done." "SIGTERM output ends Stopped"
check "$(tail -n 1 "$tmp/l6b.tsv" | cut -f4,5)" "$(printf 'end\taction=interrupted')" "SIGTERM ledger end action=interrupted"
BEDTIME_LEDGER="$L6" ./bedtime log > "$tmp/log6"
check "$(sed -n 2p "$tmp/log6")" "2026-10-13  23:00    1       1     1        15 minutes  stopped  -" "log: Starts 1, Asks 1, Granted 1, Added 15 minutes, stopped, Slept -"
BEDTIME_LEDGER="$L6" ./bedtime 23:00 --dry-run --clock-start 2026-10-13T23:01:00 > "$tmp/dry6"
sed "s#^Ledger: .*#Ledger: <temporary file>#" "$tmp/dry6" > out/restart-2-dry-run.txt
check "$(sed -n 1,7p "$tmp/dry6")" "$(cat <<'X'
Clock: simulated from 2026-10-13T23:01:00 at 1x.
Schedule of extensions, night of Tue 2026-10-13.
Resuming tonight. 1 grant given, 15 minutes in total. Bedtime is 23:15:00.
Bedtime is 23:15:00 on Tue 2026-10-13.
Asking for five more minutes opens at 23:14:00, one minute before.
Each grant is half the one before. The next grant is 7 minutes 30 seconds.
The most that can ever be granted in total is 30 minutes.
X
)" "resumed dry run opening"
check "$(grep -oE '^[0-9]+\.' "$tmp/dry6" | tr '\n' ' ')" "2. 3. 4. 5. 6. 7. " "rows start at 2"
has "$tmp/dry6" "The last possible bedtime is 23:29:45.937." "last possible bedtime unchanged"
t0=$(date +%s%N)
BEDTIME_LEDGER="$L6" ./bedtime 23:00 --clock-start 2026-10-13T23:01:00 --clock-speed 60 --then true < /dev/null > "$tmp/o6c"; rc=$?
t1=$(date +%s%N)
cp "$tmp/o6c" out/restart-3-resumed.txt
check "$rc" 0 "resumed run exits 0"
check "$(tail -n 2 "$tmp/o6c" | tr '\n' ' ')" "Bedtime. Sleeping. " "resumed run ends Bedtime. Sleeping."
check "$(tail -n 1 "$L6" | cut -c12-19)" "23:15:00" "resumed run acted at 23:15:00 (real $(((t1 - t0) / 1000000)) ms for 14 simulated minutes)"
BEDTIME_LEDGER="$L6" ./bedtime log > "$tmp/log6c"
cp "$tmp/log6c" out/restart-4-log.txt
check "$(sed -n 2p "$tmp/log6c" | sed 's/23:15:01$/23:15:00/')" "2026-10-13  23:00    2       1     1        15 minutes  then   23:15:00" "log: Starts 2, Ended then, Slept 23:15:00"
BEDTIME_LEDGER="$L6" ./bedtime 23:00 --dry-run --clock-start 2026-10-14T21:00:00 > "$tmp/dry6d"
check "$(sed -n 2,3p "$tmp/dry6d" | tr '\n' '|')" "Schedule of extensions, night of Wed 2026-10-14.|Bedtime is 23:00 on Wed 2026-10-14.|" "another night starts fresh"

echo "== 7. request handling"
{ sleep 0.3; echo 'Five More Minutes!'; sleep 6; } | BEDTIME_LEDGER="$tmp/l7a.tsv" timeout -s INT 5 ./bedtime 23:00 --clock-start 2026-10-13T22:59:10 > "$tmp/o7a"
has "$tmp/o7a" "Granted 15 minutes. Remaining that can ever be granted: 15 minutes." "case and punctuation accepted"
{ sleep 0.3; echo 'five more minutes'; sleep 6; } | BEDTIME_LEDGER="$tmp/l7b.tsv" timeout -s INT 5 ./bedtime 23:00 --clock-start 2026-10-13T22:00:00 > "$tmp/o7b"
has "$tmp/o7b" "Not yet. Asking opens at 22:59:00." "early request answered Not yet"
check "$(grep -c 'ask.result=early grant_ms=0' "$tmp/l7b.tsv")" 1 "ledger ask result=early"
{ sleep 0.3; echo 'give me an hour'; sleep 6; } | BEDTIME_LEDGER="$tmp/l7c.tsv" timeout -s INT 5 ./bedtime 23:00 --clock-start 2026-10-13T22:59:10 > "$tmp/o7c"
has "$tmp/o7c" "That is not a request this counter takes. The request is five more minutes." "other text is not a request"
check "$(grep -c "$(printf '\task\t')" "$tmp/l7c.tsv")" 0 "no ledger ask line for it"
BEDTIME_LEDGER="$tmp/l7d.tsv" ./bedtime 23:00 --clock-start 2026-10-13T22:00:00 < /dev/null > "$tmp/o7d" &
pid=$!; sleep 3
check "$(kill -0 "$pid" 2>/dev/null && echo running)" running "still running 3 s after input closed"
kill -INT "$pid"; wait "$pid"
mkdir "$tmp/home7"
out=$(env -u BEDTIME_LEDGER -u XDG_STATE_HOME HOME="$tmp/home7" ./bedtime 23:00 --clock-start 2026-10-13T22:58:00); rc=$?
check "$rc $out" "2 A simulated clock needs its own ledger. Set BEDTIME_LEDGER." "simulated clock refused without its own ledger, exit 2"
check "$(ls -A "$tmp/home7")" "" "the home folder is still empty"
out=$(./bedtime 24:00); rc=$?
check "$rc $out" "2 Bedtime must be given as HH:MM, 24-hour, for example 23:00." "unreadable time"
out=$(./bedtime 23:00 --snooze); rc=$?
check "$rc $(echo "$out" | wc -l | tr -d ' ')" "2 1" "unknown flag prints one usage line, exit 2"

echo "== 8. the action and the fallback, with stubs"
stubs="$tmp/stubs"; mkdir "$stubs"
stub() { printf '#!/bin/sh\n%s\n' "$2" > "$stubs/$1"; chmod +x "$stubs/$1"; }
night() { BEDTIME_LEDGER="$1" PATH="$stubs:$PATH" ./bedtime 23:00 --clock-start "$2" --clock-speed 60 "${@:3}" < /dev/null; }
stub systemctl 'exit 1'; stub loginctl 'exit 1'
out=$(night "$tmp/l8a.tsv" 2026-10-13T22:59:58); rc=$?
check "$rc|$(echo "$out" | tail -n 1)" "3|Neither suspend nor lock was available here. Nothing was done." "(a) both fail: message, exit 3"
check "$(tail -n 1 "$tmp/l8a.tsv" | cut -f5)" "action=none failed=suspend,lock" "(a) end action=none failed=suspend,lock"
stub systemctl "echo \"\$@\" > $stubs/systemctl.args"
night "$tmp/l8b.tsv" 2026-10-13T22:59:58 > /dev/null; rc=$?
check "$rc|$(cat "$stubs/systemctl.args")|$(tail -n 1 "$tmp/l8b.tsv" | cut -f5)" "0|suspend|action=suspend" "(b) suspend called with suspend, exit 0, end action=suspend"
rm -f "$stubs/systemctl.args"
stub loginctl "echo \"\$@\" > $stubs/loginctl.args"
night "$tmp/l8c.tsv" 2026-10-13T22:59:58 --lock > "$tmp/o8c"; rc=$?
check "$rc|$(cat "$stubs/loginctl.args")|$(test -e "$stubs/systemctl.args" || echo no-suspend)|$(tail -n 1 "$tmp/o8c")" "0|lock-session|no-suspend|Locking." "(c) --lock calls lock-session and no suspend"
rm -f "$stubs/loginctl.args"
stub systemctl 'exit 1'
night "$tmp/l8d.tsv" 2026-10-13T22:59:58 > /dev/null; rc=$?
check "$rc|$(cat "$stubs/loginctl.args")|$(tail -n 1 "$tmp/l8d.tsv" | cut -f5)" "0|lock-session|action=lock failed=suspend" "(d) suspend fails, lock works: action=lock failed=suspend"
stub systemctl 'sleep 2; exit 0'
night "$tmp/l8e.tsv" 2026-10-13T22:59:50 > /dev/null; rc=$?
BEDTIME_LEDGER="$tmp/l8e.tsv" ./bedtime log > "$tmp/log8e"
cp "$tmp/log8e" out/stub-slow-suspend-log.txt
check "$(sed -n 2p "$tmp/log8e" | awk '{print $NF}' | sed 's/23:00:01/23:00:00/')" "23:00:00" "(e) Slept is the deadline second although the stub took 120 simulated seconds"
check "$(tail -n 1 "$tmp/l8e.tsv" | cut -c12-19 | sed 's/23:00:01/23:00:00/')" "23:00:00" "(e) the end line's time is the same"

if [ "${1:-}" = "real" ]; then
  echo "== 9. real clock, real input (about two minutes)"
  target=$(date -d '+2 minutes' +%H:%M)
  BEDTIME_LEDGER="$tmp/l9.tsv" ./bedtime "$target" --then "date +%T.%3N > $tmp/out.txt" < /dev/null > "$tmp/o9"; rc=$?
  cp "$tmp/o9" out/real-clock.txt
  echo "      target $target:00, the command ran at $(cat "$tmp/out.txt")"
  check "$rc" 0 "exit 0"
  check "$(sed -n 1p "$tmp/o9" | cut -c1-16)|$(sed -n 4p "$tmp/o9")|$(tail -n 2 "$tmp/o9" | tr '\n' ' ')" \
    "Bedtime is $target|The most that can ever be granted in total is 30 minutes.|Bedtime. Sleeping. " "four opening lines, then Bedtime. Sleeping."
  late=$(awk -v t="$target" -v r="$(cat "$tmp/out.txt")" 'BEGIN { split(t, a, ":"); split(r, b, ":"); d = (b[1]*3600 + b[2]*60 + b[3]) - (a[1]*3600 + a[2]*60); print (d >= 0 && d <= 1.5) ? "yes" : "no " d }')
  check "$late" yes "the command ran 0 to 1.5 s after the target"
  check "$(tail -n 1 "$tmp/l9.tsv" | cut -f4,5)" "$(printf 'end\taction=then')" "ledger end line"
fi

[ "$fails" -eq 0 ] && echo "checks: all passed" || echo "checks: $fails failed"
exit "$fails"
