#!/bin/bash


shopt -s extglob

function run() {
  TEMPLATE="$1"
  MAINDIR="$2"

  echo "Template is $TEMPLATE, main directory is $MAINDIR"
  
  mkdir -p $MAINDIR/$TEMPLATE
  ./compile_all.py -t templates/$TEMPLATE -b $MAINDIR/$TEMPLATE
  
  for cipher in $MAINDIR/$TEMPLATE/*; do
    case $TEMPLATE in
      f7)         mv $cipher/build/f7.bin $cipher/firmware.bin
                  ;;

      maixduino)  mv $cipher/.pio/build/sipeed-maixduino/firmware.bin $cipher/firmware.bin
                  ;;

      bluepill)   mv $cipher/.pio/build/bluepill_f103c8/firmware.bin $cipher/firmware.bin
                  ;;
      
      uno)        mv $cipher/.pio/build/uno/firmware.hex $cipher/firmware.bin
                  ;;
      
      esp32)      mv $cipher/.pio/build/esp32dev/firmware.bin $cipher/firmware.bin
                  ;;
    esac                       
    rm -r $(find $cipher ! -wholename $cipher ! -name "firmware.*"  ! -name "LWC_AEAD_KAT.txt")

  done
}

if [[ $1 == "run" ]]; then
  run $2 $3
else

  MAINDIR=email-submissions/$(date +%Y-%m-%d-%H:%M)
  mkdir -p $MAINDIR
  unzip $1 -d all-lwc-submission-files
  for i in templates/*; do
    TEMPLATE="${i##*/}"
    echo "Template is $TEMPLATE"
    touch $MAINDIR/locky.lock
    flock $MAINDIR/locky.lock $0 run $TEMPLATE $MAINDIR
  done

fi


