#!/bin/bash


shopt -s extglob
export PYTHONPATH="$PYTHONPATH:$(pwd)"

function run() {
  SUBMISSION="$1"
  TEMPLATE="$2"
  DESTDIR="$3"

  if [[ ! -d "templates/$TEMPLATE" ]]; then
    echo "Template '$TEMPLATE' does not exist"
    exit 1
  fi

  if [[ -e "$DESTDIR" ]]; then
    echo "Destination directory '$DESTDIR' already exists"
    exit 1
  fi

  TMPDIR=$(mktemp -d -t build-XXXXXXXXXX)

  if [[ ! -d "$TMPDIR" ]]; then
    echo "Failed to create a temporary build directory"
    exit 1
  fi

  echo "Template is '$TEMPLATE', destination directory is '$DESTDIR', temporary directory is '$TMPDIR'"

  mkdir -p $DESTDIR
  echo "Compiling for template '$TEMPLATE' in directory '$TMPDIR'"

  TEMPLATE_PATH="templates/$TEMPLATE"

  TEMPLATE_COMMIT=$(git rev-list -1 HEAD -- "$TEMPLATE_PATH")
  if [ -z "$TEMPLATE_COMMIT" ]; then
    echo "Could not retrieve the git commit of the template"
    exit 1
  fi

  TEMPLATE_TIMESTAMP=$(git show -s --format=%ct "$TEMPLATE_COMMIT")
  if [ -z "$TEMPLATE_TIMESTAMP" ]; then
    echo "Could not retrieve the git commit date of the template"
    exit 1
  fi

  ./compile_all.py -s $SUBMISSION -t $TEMPLATE_PATH -b "$TMPDIR"
  
  for cipher in $TMPDIR/*; do
    if [[ ! -d $cipher ]]; then continue; fi

    CIPHER_SLUG=$(basename $cipher);
    FAMILY="${CIPHER_SLUG%%.*}";
    REM="${CIPHER_SLUG#*.}";
    VARIANT="${REM%%.*}";
    IMPLEMENTATION="${REM#*.}";

    CIPHER_TIMESTAMP=$(cat "$cipher/cipher_mtime.txt")

    TEST_PATH="$DESTDIR/$CIPHER_SLUG"
    mkdir -p "$TEST_PATH" || exit 1
    TEST_PATH=$(realpath $TEST_PATH)

    mv $cipher/*.log "$TEST_PATH"
    cp test_vectors/$VARIANT/LWC_AEAD_KAT_*.txt "$TEST_PATH/LWC_AEAD_KAT.txt" || exit 1
    mv $TMPDIR/$CIPHER_SLUG/*{.elf,.bin,.hex,.map} "$TEST_PATH"

    curl \
      --request 'POST' \
      --header "Content-Type: application/json" \
      --data "\
{\
\"build_dir\":\"$TEST_PATH\",\
\"cipher\":\"$CIPHER_SLUG\",\
\"cipher_timestamp\":\"$CIPHER_TIMESTAMP\",\
\"template\":\"$TEMPLATE\",\
\"template_commit\":\"$TEMPLATE_COMMIT\",\
\"template_timestamp\":\"$TEMPLATE_TIMESTAMP\"\
}" \
      "http://127.0.0.1:5002/schedule_test"

  done

  #rm -rf "$TMPDIR"
}

if [[ $1 == "run" ]]; then
  run $2 $3 $4
else
  ZIP_PATH="$1"
  if [[ ! -f $ZIP_PATH ]]; then
    echo "Error: '$ZIP_PATH' is not a zip file"
    exit 1
  fi

  MAINDIR=email-submissions/$(date +%Y-%m-%d-%H:%M)
  mkdir -p $MAINDIR
  TMPDIR=$(mktemp -d -t submission-XXXXXXXXXX)
  echo "Extracting in $TMPDIR"
  unzip $ZIP_PATH -d $TMPDIR
  for i in templates/{uno,bluepill,f7,longan-nano,esp32,maixduino}; do
    TEMPLATE="${i##*/}"
    echo "Template is $TEMPLATE"
    touch $MAINDIR/locky.lock
    flock $MAINDIR/locky.lock $0 run $TMPDIR $TEMPLATE $MAINDIR/$TEMPLATE
  done
  #rm -rf $TMPDIR

fi


