#!/bin/bash

OPTIND=1

forced=false
while getopts ":f" opt
do
  case $opt in
    f) forced=true ;;
    esac
done

shift $(($OPTIND - 1))

BOXMOX_PATH=${KPP_HOME}/boxmox

# sanity checks
if [[ $# -lt 1 ]] || [[ $# -gt 2 ]]
then
  echo "Call with <mechanism name> (<experiment path>)."
  echo "If you omit <experiment path>, a subfolder with the name <mechanism name> will be used."
  echo "Use -f to force removal of existing experiment folder."
  exit 1
fi

mech_req=$1
[ $# -eq 2 ] && path_req=$2 || path_req=$mech_req

# check if BOXMOX is correctly set up
validate_BOXMOX_installation || { echo "Validating BOXMOX installation failed"; exit 1; }

BOXMOX_MECH_PATH=${BOXMOX_PATH}/compiled_mechs

default_nml=${BOXMOX_PATH}/examples/BOXMOX.nml
mech_path=${BOXMOX_MECH_PATH}/${mech_req}
mech_exe=${mech_path}/${mech_req}.exe

# prerequisite checks
[ -f ${mech_exe} ] || { echo "Mechanism <${mech_req}> does not exist, create it with prepare_BOXMOX_mechanism first."; exit 1; }

$forced && { rm -r ${path_req}; }
[ -d ${path_req} ] && { echo "Experiment directory $path_req already exists, use -f to overwrite."; exit 1; }

mkdir $path_req
cp ${mech_exe} ${path_req}/
cp ${default_nml} ${path_req}/
echo __BOXMOX_VERSION__ > ${path_req}/VERSION

