#!/bin/sh
# The shell side of the acceptance checks in CARD.md; go test runs the flows.
# Run from the project folder on a machine with go: sh accept.sh
set -u
go build -o tipin . || exit 1
TIPIN=$(pwd)/tipin
GOROOT=$(go env GOROOT)
DOC=$GOROOT/src/fmt/doc.go
T=$(mktemp -d)
trap 'rm -rf "$T"' EXIT

echo "== 1. end to end on doc.go (go $(go env GOVERSION))"
cp "$DOC" "$T/notes.md"
cd "$T"
before="$(sha256sum notes.md) $(stat -c %y notes.md)"
$TIPIN notes.md 3 "for Friday read Thursday"
after="$(sha256sum notes.md) $(stat -c %y notes.md)"
[ "$before" = "$after" ] && echo "book sha256 and mtime unchanged: $after"
jq -r 'keys_unsorted[0]' notes.md.tipin
echo "diff of the show text against the book (empty is right):"
$TIPIN show notes.md | head -n "$(wc -l < notes.md)" | cut -c11- | diff - notes.md && echo "(no difference)"
$TIPIN show notes.md | tail -n 6
echo "first 12 of sha256sum: $(sha256sum notes.md | cut -c1-12)"
cd - >/dev/null

echo "== 4. check over the Go source tree"
/usr/bin/time -f "%e s" $TIPIN check "$GOROOT/src"
echo "exit $?"

echo "== 5. the only writes and removes in the non-test sources"
grep -nE 'O_WRONLY|O_RDWR|O_APPEND|WriteFile|Create\(|Remove' $(ls *.go | grep -v '_test.go$')

echo "== 6. print geometry"
cd "$T"
$TIPIN print notes.md > slip.txt
echo "lines: $(wc -l < slip.txt); longest: $(awk '{ if (length($0) > m) m = length($0) } END { print m }' slip.txt) runes"
sed -n '1,3p;28,30p' slip.txt
cd - >/dev/null

echo "== 9. static checks"
go vet ./... && echo "go vet: ok"
go test -count=1 ./...
echo "non-standard packages: $(go list -f '{{if not .Standard}}{{.ImportPath}}{{end}}' -deps ./... | tr '\n' ' ')"
grep -c require go.mod
grep -rln "$(printf '\342\200\224')" . ; echo "em dash files: $(grep -rl "$(printf '\342\200\224')" . | wc -l)"
echo "net imports: $(grep -n '"net' *.go | wc -l)"
echo "non-ASCII bytes in Go sources: $(cat *.go | LC_ALL=C grep -c '[^ -~	]')"

echo "== 10. output audit over out/"
echo "escape bytes in out/: $(cat out/*.txt | LC_ALL=C grep -c "$(printf '\033')")"
echo "em dashes in out/: $(cat out/*.txt | grep -c "$(printf '\342\200\224')")"
rm -f tipin
