#!/bin/bash


shopt -s extglob

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

  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 -t "templates/$TEMPLATE" -b "$TMPDIR"
  
  for cipher in $TMPDIR/*; do
    CIPHER_SLUG=$(basename $cipher)
    if [[ ! -d $cipher ]]; then continue; fi
    mkdir -p $DESTDIR/$CIPHER_SLUG || exit 1
    mv $cipher/*.log $DESTDIR/$CIPHER_SLUG/

    case $TEMPLATE in
      f7)         mv $cipher/build/f7.* $DESTDIR/$CIPHER_SLUG/
                  ;;

      maixduino)  mv $cipher/.pio/build/sipeed-maixduino/firmware.* $DESTDIR/$CIPHER_SLUG/
                  ;;

      bluepill)   mv $cipher/.pio/build/bluepill_f103c8/firmware.* $DESTDIR/$CIPHER_SLUG/
                  ;;
      
      uno)        mv $cipher/.pio/build/uno/firmware.* $DESTDIR/$CIPHER_SLUG/
                  ;;
      
      esp32)      mv $cipher/.pio/build/esp32dev/firmware.* $DESTDIR/$CIPHER_SLUG/
                  ;;
    esac

  done

  rm -rf "$TMPDIR"
}

if [[ $1 == "run" ]]; then
  run $2 $3
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
  unzip $ZIP_PATH -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/$TEMPLATE
  done

fi


