#!/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'"
  ./compile_all.py -s $SUBMISSION -t "templates/$TEMPLATE" -b "$TMPDIR"
  
  for cipher in $TMPDIR/*; do
    if [[ ! -d $cipher ]]; then continue; fi

    mkdir -p "./queues"
    QUEUE_PATH="./queues/$TEMPLATE"
    CIPHER_SLUG=$(basename $cipher)
    TEST_PATH="$DESTDIR/$CIPHER_SLUG"

    mkdir -p "$TEST_PATH" || exit 1
    mv $cipher/*.log "$TEST_PATH"
    mv "$cipher/LWC_AEAD_KAT.txt" "$TEST_PATH"

    case $TEMPLATE in
      f7)         mv $cipher/build/f7.* "$TEST_PATH"
                  ;;

      maixduino)  mv $cipher/.pio/build/sipeed-maixduino/firmware.* "$TEST_PATH"
                  ;;

      bluepill)   mv $cipher/.pio/build/bluepill_f103c8/firmware.* "$TEST_PATH"
                  ;;
      
      uno)        mv $cipher/.pio/build/uno/firmware.* "$TEST_PATH"
                  ;;
      
      esp32)      mv $cipher/.pio/build/esp32dev/firmware.* $cipher/.pio/build/esp32dev/partitions.bin "$TEST_PATH"
                  ;;
    esac

    curl \
      --request 'POST' \
      --header "Content-Type: application/json" \
      --data "{\"path\":\"$(realpath $TEST_PATH)\",\"template\":\"$TEMPLATE\"}" \
      "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)
  unzip $ZIP_PATH -d $TMPDIR
  for i in templates/*; 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


