#!/bin/sh
DOCUMENTATION=$(cat <<END_OF_DOCUMENTATION
ptest 1.2

A shell script to locally test solutions to competitive programming
problems.

USAGE: ptest [OPTIONS] PROGRAM

Where the OPTIONS are:
  --help
    Outputs this manual-style help message and immediately exits.

  --version
    Outputs the script name along with its version number.

Where PROGRAM is the program that should be run.  This scripts expects
a shebang on the first line of the script.

SPDX-FileCopyrightText: Copyright (c) 2021, Theodore Preduta.
SPDX-License-Identifier: BSD-2-Clause
END_OF_DOCUMENTATION
)

set -e

usage() {
  [ -n "$1" ] && echo "$1" && echo

  echo "Usage: ptest [OPTIONS] PROGRAM"
  echo "Try running with --help for more information."

  exit 1
}

while [ ! "$*" = "" ]; do
  case "$1" in
    --help)
      echo "$DOCUMENTATION"
      exit 0;;
    --version)
      echo "$DOCUMENTATION" | head -n 1
      exit 0;;
    *)
      target="$1"
      shift 1;;
  esac
done

RED='\033[0;31m'
GREEN='\033[0;32m'
NC='\033[0m'

target_interpreter=$(sed -n '1s/^#!//p' "$target")

total_pass=0
total_fail=0

for f in $(find "data" -type f -name \*.in | cut -f 1 -d '.'); do
  printf "%s..." "$f"
  
  if $target_interpreter "$target" < "$f.in" | cmp -s - "$f.out"; then
    printf "${GREEN}PASS${NC}\n"
    total_pass=$(( total_pass + 1 ))
  else
    printf "${RED}FAIL${NC}\n"
    total_fail=$(( total_fail + 1 ))
  fi
done

echo
echo "Passed: $total_pass"
echo "Failed: $total_fail"
