#!/usr/bin/env bash

DIR=`dirname ${0}`
TOOLPATH=${DIR}/run-tool

PROBNAME="Astral Geometry"
INPUTSPEC="The first line of an input file should contain an integer n.
After that, n lines should follow.
The i-th line of them should contain three integers x, y, and z, representing the coordinates of star i."

if (( $# < 1 ))
then
  echo "Local testing tool for ${PROBNAME}"
  echo ""
  echo "Usage:"
  echo "  $ ${TOOLPATH} [--silent] input-file exec-command ..."
  echo ""
  echo "By default, the outputs from an interactor and an author's program are written to the standard error."
  echo "Adding --silent option will suppress the output."
  echo ""
  echo "Sample input files are available under \"${DIR}\"."
  echo ""
  echo "Example commands for executing the tool:"
  echo "  $ ${TOOLPATH} ${DIR}/1.in runcpp main.out"
  echo "  $ ${TOOLPATH} ${DIR}/1.in runjava Main"
  echo "  $ ${TOOLPATH} ${DIR}/1.in runpython3 main.py"
  echo ""
  echo "${INPUTSPEC}"
  echo ""
  echo "NOTE: The testing tool is built on the same judging code as the real judging system."
  echo "The difference is that, while this tool runs on your local machine, judging in the real system is"
  echo "performed in a sandboxed environment. Results may differ for programs with undefined or"
  echo "environment-dependent behavior. The testing tool does not apply time or memory limits."
  echo ""
  exit 1
fi

if [[ $1 == "--silent" ]]
then
  ENV_PARAM='-u INTERACTOR_VERBOSE USING_HELPER=1'
  shift
else
  ENV_PARAM='INTERACTOR_VERBOSE=1 USING_HELPER=1'
fi

INP=$1
shift

ANS=$INP

COMMAND=$@
FEEDBACK=`mktemp -d /tmp/__feedback_XXXXXXXXXX`
FIFO="${FEEDBACK}/__fifo"
LOG=/tmp/interactor.log
INTERACTOR=${DIR}/interactor.out

mkfifo ${FIFO}

if [[ ! -f $INTERACTOR ]]
then
  g++ ${DIR}/interactor.cc -O2 -std=gnu++20 -o ${INTERACTOR}
fi

cat <<EOF >> $LOG
{"time":"$(date +"%Y-%m-%d %H:%M:%S")", "state":"start", "dir": "${FEEDBACK}"}
EOF

$COMMAND < ${FIFO} | env ${ENV_PARAM} ${INTERACTOR} ${INP} ${ANS} ${FEEDBACK} > ${FIFO}
RET=$?

JUDGEMES_FILE=${FEEDBACK}/judgemessage.txt
JUDGEERR_FILE=${FEEDBACK}/judgeerror.txt

if [[ -f ${JUDGEMES_FILE} ]]
then
  JUDGEMES=`cat $JUDGEMES_FILE`
fi
if [[ -f ${JUDGEERR_FILE} ]]
then
  JUDGEERR=`cat $JUDGEERR_FILE`
fi

if [[ "$RET" = 42 ]]
then
  VERDICT="CORRECT"
elif [[ "$RET" = 43 ]]
then
  VERDICT="WRONG ANSWER"
else
  VERDICT="RUN ERROR (EXIT CODE = $RET)"
fi

echo "VERDICT: ${VERDICT}"

cat <<EOF >> $LOG
{"time":"$(date +"%Y-%m-%d %H:%M:%S")", "state":"end", "dir": "${FEEDBACK}", "exit_code":$RET, "judge_message":"${JUDGEMES}", "judge_error":"${JUDGEERR}", "verdict":"$VERDICT"}
EOF

rm -rf "${FEEDBACK}"

exit $RET
