#!/usr/bin/env bash
# labcheck: checks the Go lab of the KaliRange course "Go for security tools".
ready=0

# 1. go runs
if go version >/dev/null 2>&1; then
  echo "1 ok    go runs"
  ready=$((ready + 1))
else
  echo "1 FAIL  go does not run (is it on your PATH?)"
fi

# 2. the version is 1.22 or later
ver=$(go env GOVERSION 2>/dev/null | sed 's/^go//')
major=${ver%%.*}
rest=${ver#*.}
minor=${rest%%[!0-9]*}
case $major in ''|*[!0-9]*) minor="" ;; esac
if [ -n "$minor" ] && { [ "$major" -gt 1 ] || [ "$minor" -ge 22 ]; }; then
  echo "2 ok    go is 1.22 or later"
  ready=$((ready + 1))
else
  echo "2 FAIL  go is older than 1.22 or its version is unknown"
fi

# 3. a tiny program builds and runs
dir=$(mktemp -d)
cat > "$dir/main.go" <<'GO'
package main

import "fmt"

func main() { fmt.Println("lab-ok") }
GO
printf 'module labtest\n\ngo 1.22\n' > "$dir/go.mod"
if [ "$(cd "$dir" && go run . 2>/dev/null)" = "lab-ok" ]; then
  echo "3 ok    a program builds and runs"
  ready=$((ready + 1))
else
  echo "3 FAIL  a program did not build and run"
fi

# 4. the race detector works (it needs a C compiler)
if [ "$(cd "$dir" && go run -race . 2>/dev/null)" = "lab-ok" ]; then
  echo "4 ok    the race detector works"
  ready=$((ready + 1))
else
  echo "4 FAIL  the race detector does not work (is a C compiler installed?)"
fi
rm -rf "$dir"

echo "lab ready: $ready of 4"
[ "$ready" -eq 4 ]
