#!/bin/bash

BIN=bin
VER=`cabal info . | head -1 | grep -Eo "[0-9.]+"`

function make_package {
    PKG=lustre-sally-$VER
    cabal v2-install --installdir="$BIN" --install-method=copy --overwrite-policy=always
    rm -rf                   $PKG
    mkdir                    $PKG
    mkdir                    $PKG/bin
    mkdir                    $PKG/doc
    cp bin/lustre-sally      $PKG/bin
    cp README.md             $PKG/doc
    cp example/farmer.pdf    $PKG/doc
    tar -czvf $PKG.tar.gz    $PKG
    rm -rf                   $PKG
}

function setup_external_tools {
  if [ ! -f "$BIN/test-runner" ]
  then
    mkdir -p "$BIN"
    cabal v2-install --installdir="$BIN" test-lib
  fi
}

function show_usage {
cat <<EOM
Usage: $0 COMMAND COMANND_OPTIONS
Available commands:
  build     Build project
  test      Run some tests
  run       Run lustre-sally
EOM
}




if [ "$#" == "0" ]
then
  show_usage
  exit 1
fi

COMMAND=$1
shift

case $COMMAND in
  build)
    echo Building project
    cabal v2-build exe:lustre-sally;;

  test)
    echo Running tests
    setup_external_tools
    if [ "$#" == "0" ]
      then TESTS=tests
      else TESTS=$*
    fi
    $BIN/test-runner --ext=.lus \
                     --exe=./build-utils/run-one-test \
                     $TESTS
    ;;

  run)
    cabal v2-run exe:lustre-sally -- $@
    ;;

  package)
    make_package
    exit 0;;

  help)
    show_usage
    exit 0;;

  *)
    echo Unrecognized command: $COMMAND
    show_usage
    exit 1;;

esac



