#!/bin/bash

problem=demo
author=ek
#you can set lang as dpr, java, cpp or python
lang=cpp

echo Generating tests...
rm -rf tests
cd src
javac Tests.java
java -Xmx256M -Xss64M -ea Tests
rm *.class
cd ..

echo Compiling checker...

rm -rf __tmp 2> /dev/null
mkdir __tmp
javac -classpath "../../lib/testlib4j.jar" -sourcepath . -d __tmp Check.java
#javac -classpath "__check;%../../lib/testlib4j.jar" -sourcepath . -d __tmp Check.java
cp ../../lib/testlib4j.jar __tmp/    > /dev/null
pushd __tmp
jar xf testlib4j.jar
echo Main-Class: ru.ifmo.testlib.CheckerFramework> META-INF/manifest.1
echo Checker-Class: Check>> META-INF/manifest.1
rm -f *.java > /dev/null
rm testlib4j.jar > /dev/null
jar cfm check.jar META-INF/manifest.1 *.class ru
cp check.jar .. > /dev/null
popd
rm -rf __tmp

echo Compiling validator...

rm -rf __tmp 2> /dev/null
mkdir __tmp
javac -classpath "../../lib/validate4j.jar" -sourcepath . -d __tmp Validate.java
cp ../../lib/validate4j.jar __tmp/    > /dev/null
pushd __tmp
jar xf validate4j.jar
echo Main-Class: ru.ifmo.validate.ValidatorFramework> META-INF/manifest.1
echo Checker-Class: Validate>> META-INF/manifest.1
jar cfm validate.jar META-INF/manifest.1 *.class ru
cp validate.jar .. > /dev/null
popd
rm -rf __tmp

echo Generating answers...

if [ "${lang}" == "java" ]; then
  javac ${problem}_${author}.java -encoding utf8
fi
if [ "${lang}" == "cpp" ]; then 
  g++ -O2 -std=c++11 ${problem}_${author}.cpp -o ${problem}_${author}.exe
fi
if [ "$lang"=="dpr" ]; then
#dcc32 -cc ${problem}_${author}.dpr
  echo "dcc32 not found"
fi

for i in `find tests/ | sort -n | grep tests/..$`;
do
    echo Test $i
    cp $i ${problem}.in > /dev/null
    java -jar validate.jar < ${problem}.in
    if [ $? -ne 0 ]; then
        echo Validator rejects test $i
        exit
    fi;
    echo Validator accepts test $i

    if [ "$lang" == "java" ]; then
      java -Xmx256M -Xss64M ${problem}_${author}
    fi
    if [ "$lang" == "cpp" ]; then
      ./${problem}_${author}.exe
    fi
    if [ "$lang" == "dpr" ]; then
      ./${problem}_${author}.exe
    fi
    if [ "$lang" == "python" ]; then
      python ${problem}_${author}.py
    fi

    cp ${problem}.out ${i}.a > /dev/null
    echo Check $i
    java -jar check.jar $i ${i}.a ${i}.a
done

rm -f ${problem}.in ${problem}.out
