#!/bin/sh

bold_white=""
bold_green=""
bold_red=""
end=""

bin_name=$(basename `pwd`)

dev_build_steps=("test" "build")
prod_build_steps=("build" "strip")

build_steps=("${dev_build_steps[@]}")
compiler_defines=""
common_compiler_flags="-debug -vet -strict-style -warnings-as-errors"
for arg in "$@"; do
  case $arg in
    -release)
      common_compiler_flags="-o:speed -no-bounds-check -disable-assert -extra-linker-flags:"-Wl,--gc-sections""
      build_steps=("${prod_build_steps[@]}")
    ;;

    *)
      echo "${bold_red}Unknown parameter \"${arg}\".${end}"
      exit -1
    ;;
  esac
done

compiler_flags="${compiler_defines} ${common_compiler_flags}"
echo "${bold_white}Using compiler flags:${end} ${compiler_flags}"

if [ ! -d build ]; then
  mkdir build
fi
pushd build 1>/dev/null 2>&1

for step in ${!build_steps[@]}; do
  case ${build_steps[$step]} in
    "test")
      echo ""
      echo "${bold_white}Running tests${end}"
      odin test ../src $compiler_flags
      result=$?
      if [ $result -ne 0 ]; then
        echo "${bold_red}FAIL${end}"
        exit $result
      fi
      echo ""
    ;;

    "build")
      echo "${bold_white}Building:${end} $(pwd)/$bin_name"
      odin build ../src -out:$bin_name -show-timings $compiler_flags
      result=$?
      if [ $result -ne 0 ]; then
        echo "${bold_red}FAIL${end}"
        exit $result
      fi

      echo ""
      echo "${bold_green}OK${end}"
    ;;

    "strip")
      strip -s $(pwd)/$bin_name
    ;;

    *)
    ;;
  esac
done

popd 1>/dev/null 2>&1