#!/usr/bin/env bash
# The acceptance run from CARD.md (checks 1 to 6 and 8 to 10, plus the card's
# three screenshots for check 7), on the real clock with real files, curl and
# headless Chromium. It takes about eight minutes, most of it waiting for the
# opening. Run from the project folder: scripts/e2e.sh
# CHROMIUM=/path/to/chrome picks the browser. PDFs go to out/, shots to shots/.
set -u
cd "$(dirname "$0")/.."
mkdir -p out shots
export TZ=${TZ:-Europe/Berlin} LC_ALL=C
CH=${CHROMIUM:-$(command -v chromium || command -v chromium-browser || ls -d "$HOME"/.cache/ms-playwright/chromium-*/chrome-linux*/chrome 2>/dev/null | tail -1)}
W=$(mktemp -d)
BIN=$W/opens-fridays
trap 'for f in "$W"/*.pid; do [ -f "$f" ] && kill "$(cat "$f")" 2>/dev/null; done; rm -rf "$W"' EXIT

pass=0
fail=0
check() { # check <label> <command...>
	local label=$1
	shift
	if "$@"; then pass=$((pass + 1)); echo "PASS  $label"; else fail=$((fail + 1)); echo "FAIL  $label"; fi
}
has() { grep -qF -e "$2" "$1"; }
lacks() { ! grep -qF -e "$2" "$1"; }
py() { uv run --no-project python "$@"; }
holds() { py -c 'import sys; sys.exit(sys.argv[2] not in open(sys.argv[1]).read())' "$1" "$2"; }
is() { [ "$1" = "$2" ]; }
get() { curl -s "http://127.0.0.1:$1$2" >"$3"; }
post() { curl -s -o "$W/last.html" -w '%{http_code}' --data-urlencode "note=$2" "http://127.0.0.1:$1/put"; }
start() { # start <name> <port> [-opens value]
	"$BIN" -addr ":$2" -data "$W/$1" -opens "${3:-$OPENS}" -window 2m >>"$W/$1.log" 2>&1 &
	echo $! >"$W/$1.pid"
	for _ in $(seq 50); do curl -s -o /dev/null "http://127.0.0.1:$2/" && return; sleep 0.1; done
	echo "server $1 did not answer"
}
stop() { local p; p=$(cat "$W/$1.pid"); kill "$p"; wait "$p" 2>/dev/null; rm -f "$W/$1.pid"; }
until_epoch() { while [ "$(date +%s)" -lt "$1" ]; do sleep 1; done; }
pdf() { timeout 60 "$CH" --headless --no-sandbox --disable-gpu --no-pdf-header-footer --print-to-pdf="$2" "$1" >/dev/null 2>&1; }
shot() { timeout 60 "$CH" --headless --no-sandbox --disable-gpu --hide-scrollbars --window-size="$2" ${4:-} --screenshot="$3" "$1" >/dev/null 2>&1; }
pages() { pdfinfo "$1" | awk '/^Pages:/ {print $2}'; }
size_is() { pdfinfo "$1" | awk -v w="$2" -v h="$3" '/^Page size:/ {d1=$3-w; d2=$5-h; ok=(d1*d1<1 && d2*d2<1)} END {exit !ok}'; }
before() { awk -v a="$2" -v b="$3" 'index($0,a) && !x {x=NR} index($0,b) && !y {y=NR} END {exit !(x && y && x < y)}' "$1"; }

echo "== 1. vet, tests, no requires, no address reading"
check "1 go vet" go vet ./...
check "1 go test" go test -count=1 ./...
check "1 go.mod has no require lines" lacks go.mod require
check "1 no RemoteAddr, X-Forwarded or log.Print in Go files" bash -c '! grep -n "RemoteAddr\|X-Forwarded\|log.Print" *.go'
go build -o "$BIN" . || exit 1

echo "== 4. unspecified hosts are replaced"
for addr in 0.0.0.0:8080 :8080; do
	"$BIN" -addr "$addr" -data "$W/u" >"$W/u.log" 2>&1 &
	p=$!
	sleep 1
	kill "$p"
	wait "$p" 2>/dev/null
	echo "  -addr $addr printed: $(cat "$W/u.log")"
	check "4 -addr $addr prints one line with a host that is not 0.0.0.0" bash -c "[ \$(wc -l <'$W/u.log') = 1 ] && grep -Eq '^http://[0-9.]+:8080  Opens Fridays 16:00  ' '$W/u.log' && ! grep -q '0\.0\.0\.0\|127\.0\.0\.1' '$W/u.log'"
done

# The opening: about three minutes ahead, on a whole minute, with no full hour
# between the start and the opening (an hourly snapshot would change N).
s=$((10#$(date +%M) * 60 + 10#$(date +%S)))
if [ $s -lt 90 ] || [ $s -gt 3150 ]; then
	echo "== waiting for a quieter minute ($(date +%H:%M:%S))"
	until_epoch $(($(date +%s) + (s < 90 ? 90 - s : 3690 - s)))
fi
OPEN=$(((($(date +%s) + 180) / 60 + 1) * 60))
OPENS="$(date -d @$OPEN +%a) $(date -d @$OPEN +%H:%M)"
HM=$(date -d @$OPEN +%H:%M)
KEY=$(date -d @$OPEN +%F)
NEXT=$(date -d "$KEY + 7 days" +%F)
PLATE="Opens $(date -d @$OPEN +%A)s $HM"
echo "== opening: -opens \"$OPENS\" ($TZ), box $KEY, next box $NEXT"

start a 8181
start b 8182
start c 8183
start d 8184

echo "== 2. before the opening"
get 8181 / "$W/a0.html"
check "2 plate shown: $PLATE" has "$W/a0.html" "<h1 class=\"plate\">$PLATE</h1>"
check "2 no sheet after the first start" lacks "$W/a0.html" "Opened"
check "2 $KEY.json exists as [] before any post" is "$(tr -d ' \n' <"$W/a/$KEY.json")" "[]"
for n in "zebra crossing is unclear" "$(printf 'apple  pie\n\nfriday')" "mango"; do
	check "2 POST /put answers 303" is "$(post 8181 "$n")" 303
done
get 8181 / "$W/a1.html"
check "2 notes are not shown before the opening" bash -c "! grep -q 'zebra\|apple\|mango' '$W/a1.html'"
check "2 the count has not moved without a snapshot" has "$W/a1.html" "0 notes inside."
shot http://127.0.0.1:8181/ 390,844 shots/e2e-front-390x844.png
shot http://127.0.0.1:8181/ 1280,800 shots/e2e-front-1280x800.png
shot http://127.0.0.1:8181/ 1280,800 shots/e2e-front-1280x800-force-dark.png --force-dark-mode

echo "== 3. the file"
F=$W/a/$KEY.json
echo "  $(tr -d '\n' <"$F")"
check "3 the file is a JSON array of strings in the order apple, mango, zebra" py -c 'import json,sys; d=json.load(open(sys.argv[1])); sys.exit(d != ["apple pie friday", "mango", "zebra crossing is unclear"])' "$F"
check "3 no timestamp inside the file" bash -c "! grep -Eq '[0-9]{2}[-:][0-9]{2}' '$F'"
stat -c "%A %y %n" "$W/a" "$F" | sed "s|$W/||; s|^|  |"
check "3 file mtime is the opening instant" is "$(stat -c %Y "$F")" "$OPEN"
check "3 data directory mtime is the opening instant" is "$(stat -c %Y "$W/a")" "$OPEN"

echo "== 2. restart: the startup snapshot"
m1=$(date +%H:%M)
stop a
start a 8181
m2=$(date +%H:%M)
get 8181 / "$W/a2.html"
check "2 after the restart: 3 notes inside." has "$W/a2.html" "3 notes inside."
check "2 stamped with the restart minute ($m1 or $m2)" bash -c "grep -q 'Count as of $m1\.\|Count as of $m2\.' '$W/a2.html'"
check "2 no sheet after the restart" lacks "$W/a2.html" "Opened"

echo "== 5b. post three, restart, post kettle"
for n in "fewer meetings on monday" "more light in the stairwell" "a longer lunch on thursdays"; do post 8182 "$n" >/dev/null; done
stop b
start b 8182
check "5b kettle posted after the restart" is "$(post 8182 kettle)" 303

echo "== 9. fifty parallel posts"
pids=()
for i in $(seq -w 1 50); do
	curl -s -o /dev/null -w '%{http_code}\n' --data-urlencode "note=parallel note $i" http://127.0.0.1:8183/put >>"$W/codes" &
	pids+=($!)
done
wait "${pids[@]}"
check "9 all fifty answered 303" is "$(grep -c '^303$' "$W/codes")" 50
check "9 exactly 50 notes in a valid JSON array" py -c 'import json,sys; d=json.load(open(sys.argv[1])); sys.exit(not (len(d) == 50 and all(isinstance(x, str) for x in d)))' "$W/c/$KEY.json"

echo "== 8. input handling"
C=$W/c/$KEY.json
sum() { sha256sum "$C" | cut -c1-64; }
check "8 empty note: 400" is "$(post 8183 '   ')" 400
check "8 empty note: Nothing was written." has "$W/last.html" "Nothing was written."
h=$(sum)
long="<b>  $(head -c 497 /dev/zero | tr '\0' y)"
check "8 501 characters after flattening: 413" is "$(post 8183 "$long")" 413
check "8 413 keeps the text escaped and unflattened in the textarea" py -c 'import sys; b=open(sys.argv[1]).read(); sys.exit(">\n&lt;b&gt;  " + "y"*497 + "</textarea>" not in b)' "$W/last.html"
check "8 413 leaves the box unchanged" is "$(sum)" "$h"
head -c 8995 /dev/zero | tr '\0' a | sed 's/^/note=/' >"$W/big"
check "8 a 9000 byte body: 413" is "$(curl -s -o "$W/last.html" -w '%{http_code}' --data-binary @"$W/big" http://127.0.0.1:8183/put)" 413
check "8 9000 byte body: the same 413 page, textarea empty" py -c 'import sys; b=open(sys.argv[1]).read(); sys.exit(not ("That is 500 characters at most." in b and ">\n</textarea>" in b))' "$W/last.html"
check "8 9000 byte body leaves the box unchanged" is "$(sum)" "$h"
check "8 a script note is accepted" is "$(post 8183 '<script>alert(1)</script>')" 303
check "8 the script note is stored as text" has "$C" '"<script>alert(1)</script>"'
h=$(sum)
check "8 cross-site post: 403" is "$(curl -s -o "$W/last.html" -w '%{http_code}' -H 'Sec-Fetch-Site: cross-site' -d note=x http://127.0.0.1:8183/put)" 403
check "8 cross-site post: Notes are put in from this page only." has "$W/last.html" "Notes are put in from this page only."
check "8 cross-site post leaves the box unchanged" is "$(sum)" "$h"
check "8 same-origin post: 303" is "$(curl -s -o /dev/null -w '%{http_code}' -H 'Sec-Fetch-Site: same-origin' -d note=x http://127.0.0.1:8183/put)" 303
n=$(py -c 'import json,sys; print(len(json.load(open(sys.argv[1]))))' "$C")
for i in $(seq $((n + 1)) 100); do post 8183 "filling the box, note $i" >/dev/null; done
check "8 the box holds 100" is "$(py -c 'import json,sys; print(len(json.load(open(sys.argv[1]))))' "$C")" 100
check "8 the 101st note: 409" is "$(post 8183 'one more than the box holds')" 409
check "8 409 keeps the text in the textarea" holds "$W/last.html" ">
one more than the box holds</textarea>"

echo "== 6. a full box of 200-character notes, for the A4 measure"
for i in $(seq -w 1 100); do
	t="n$i measured filler for the print test of the opened sheet, written by the tester, one note of exactly two hundred characters each time, measured filler for the print test of the opened sheet, again and again"
	post 8184 "${t:0:199}." >/dev/null
done
check "6 measure box holds 100 notes of 200 characters" py -c 'import json,sys; d=json.load(open(sys.argv[1])); sys.exit(not (len(d) == 100 and {len(x) for x in d} == {200}))' "$W/d/$KEY.json"

check "setup finished before the opening" test "$(date +%s)" -lt "$OPEN"
echo "== waiting for the opening at $HM"
until_epoch $((OPEN + 3))

echo "== 5a. the opening"
get 8181 / "$W/a3.html"
check "5a Opened header" has "$W/a3.html" "Suggestion box. Opened $(date -d @$OPEN '+%A %-d %B %Y, %H:%M')."
check "5a 3 notes, then directly the count at opening: 3" has "$W/a3.html" '<p class="total">3 notes.</p><p class="at-opening">Count shown on the page at opening: 3.</p>'
check "5a order: apple, mango, zebra" bash -c "awk '/<li>/' '$W/a3.html' | tr -d '\n' | grep -q '<li>apple pie friday</li><li>mango</li><li>zebra crossing is unclear</li>'"
check "5a treatment line" has "$W/a3.html" "Treatment: whitespace flattened, sorted by character code, nothing else changed."
check "5a new box: 0 notes inside." has "$W/a3.html" '<p class="count">0 notes inside.</p>'
check "5a stamp is the opening time $HM" has "$W/a3.html" "Count as of $HM."
check "5a the sheet comes before the box" before "$W/a3.html" 'class="sheet"' 'class="box"'
check "5a data holds $KEY.opened.json and $NEXT.json only" is "$(ls "$W/a" | tr '\n' ' ')" "$KEY.opened.json $NEXT.json "
check "5a a fourth note: 303" is "$(post 8181 'a fourth note after the opening')" 303
get 8181 / "$W/a4.html"
check "5a the fourth note is not in the list" lacks "$W/a4.html" "a fourth note"
check "5a and not yet counted" has "$W/a4.html" "0 notes inside."
get 8182 / "$W/b3.html"
check "5b 4 notes, then directly the count at opening: 3" has "$W/b3.html" '<p class="total">4 notes.</p><p class="at-opening">Count shown on the page at opening: 3.</p>'
check "5b new box 0 notes inside., stamped $HM" bash -c "grep -q '0 notes inside.' '$W/b3.html' && grep -q 'Count as of $HM.' '$W/b3.html'"
get 8183 / "$W/c3.html"
check "8 the script note is shown as text" has "$W/c3.html" "<li>&lt;script&gt;alert(1)&lt;/script&gt;</li>"
check "8 and never as a script element" lacks "$W/c3.html" "<script>alert"

echo "== 6. print"
pdf http://127.0.0.1:8181/ out/sheet.pdf
pdftotext out/sheet.pdf "$W/sheet.txt"
check "6 the sheet prints on exactly 1 page" is "$(pages out/sheet.pdf)" 1
check "6 the sheet is A4" size_is out/sheet.pdf 595.28 841.89
check "6 the sheet holds the three notes" bash -c "grep -q 'apple pie friday' '$W/sheet.txt' && grep -q mango '$W/sheet.txt' && grep -q 'zebra crossing is unclear' '$W/sheet.txt'"
check "6 the sheet carries the treatment" has "$W/sheet.txt" "Treatment: whitespace flattened, sorted by character code"
check "6 the sheet has no form" lacks "$W/sheet.txt" "Put it in"
URL=$(head -1 "$W/a.log" | cut -d' ' -f1)
pdf http://127.0.0.1:8181/plate out/plate.pdf
pdftotext out/plate.pdf "$W/plate.txt"
check "6 the door card prints on exactly 1 page" is "$(pages out/plate.pdf)" 1
check "6 the door card is A6 (105 x 148 mm)" size_is out/plate.pdf 297.64 419.53
check "6 the door card holds the plate" has "$W/plate.txt" "$PLATE"
check "6 the door card holds the startup URL $URL" has "$W/plate.txt" "$URL"
check "6 the door card has no count and no form" bash -c "! grep -q 'notes inside\|Put it in' '$W/plate.txt'"
pdf http://127.0.0.1:8183/ out/sheet-100-short.pdf
pdf http://127.0.0.1:8184/ out/sheet-100-measure.pdf
pdftotext -f 1 -l 1 out/sheet-100-measure.pdf "$W/m1.txt"
fit=$(grep -o 'n[0-9][0-9][0-9] measured' "$W/m1.txt" | sort | tail -1 | cut -c2-4)
echo "  MEASURE: notes n001 to n$fit of 100 (200 characters each) are on page 1 of $(pages out/sheet-100-measure.pdf); 100 short notes print on $(pages out/sheet-100-short.pdf) page(s)"
shot http://127.0.0.1:8181/ 1280,800 shots/e2e-opened-1280x800.png
for f in sheet plate sheet-100-measure; do pdftoppm -r 70 -png out/$f.pdf shots/print-$f; done

echo "== 10. retention"
SHOWN=$(stat -c %Y "$W/a/$KEY.opened.json")
echo "  first shown at $(date -d @$SHOWN +%T), window 2m"
until_epoch $((SHOWN + 60))
m1=$(date +%H:%M)
stop a
start a 8181
m2=$(date +%H:%M)
get 8181 / "$W/a5.html"
check "10 a restart in the window still shows the sheet" has "$W/a5.html" "Opened"
check "5 after a restart the count at opening is unknown and left off" lacks "$W/a5.html" "Count shown on the page at opening"
check "5a the fourth note is counted at the restart" bash -c "grep -q '1 note inside.' '$W/a5.html' && grep -q 'Count as of $m1\.\|Count as of $m2\.' '$W/a5.html'"
check "10 the opened file was not re-stamped by the restart" is "$(stat -c %Y "$W/a/$KEY.opened.json")" "$SHOWN"
until_epoch $((SHOWN + 115))
check "10 the opened file is still there at +115 s" test -f "$W/a/$KEY.opened.json"
until_epoch $((SHOWN + 124))
check "10 at +124 s no .opened.json remains" bash -c "! ls '$W/a' | grep -q opened"
check "10 the next box's file is still there" test -f "$W/a/$NEXT.json"
get 8181 / "$W/a6.html"
check "10 GET / shows no list" bash -c "! grep -q 'Opened\|<li>' '$W/a6.html'"

echo "== 4. one line per start, no addresses, no note text"
sed 's/^/  /' "$W/a.log"
check "4 server A printed exactly one line for each of its 3 starts" is "$(wc -l <"$W/a.log")" 3
check "4 every line is URL, plate, zone with a non-loopback IPv4" bash -c "! grep -Ev '^http://([0-9]+\.){3}[0-9]+:8181  $PLATE  $TZ\$' '$W/a.log' && ! grep -q '127\.0\.0\.1\|::1\|zebra\|apple\|mango\|fourth' '$W/a.log'"
check "4 servers B, C, D printed one line per start" is "$(cat "$W/b.log" "$W/c.log" "$W/d.log" | wc -l)" 4
for path in / /static/style.css /plate; do
	curl -sI "http://127.0.0.1:8181$path" >"$W/head"
	check "4 HEAD $path: no-store, no Last-Modified, no ETag" bash -c "grep -qi '^Cache-Control: no-store' '$W/head' && ! grep -qi '^Last-Modified\|^ETag' '$W/head'"
done

echo "== e2e: $pass passed, $fail failed"
[ "$fail" = 0 ]
