#!/usr/bin/env bash

set -Eeuo pipefail

# --- styling (only if stdout is a terminal) ---
if [[ -t 1 ]]; then
  bold_white=$'\033[1;37m'
  bold_green=$'\033[1;32m'
  bold_red=$'\033[1;31m'
  end=$'\033[0m'
else
  bold_white='' bold_green='' bold_red='' end=''
fi

die() { printf '%s\n' "${bold_red}$*${end}" >&2; exit 1; }

need_cmd() { command -v "$1" >/dev/null 2>&1 || die "Missing required command: $1"; }

run() {
  # prints the command (optional; keep quiet if you prefer)
  "$@"
}

# --- config ---
bin_name="${PWD##*/}"

dev_steps=(test build)
prod_steps=(build strip)

build_steps=("${dev_steps[@]}")

compiler_defines=() # keep as array for easy future extension

common_flags=(-debug -vet -strict-style -warnings-as-errors)
release_flags=(-o:speed -no-bounds-check -disable-assert -extra-linker-flags:-Wl,--gc-sections)

# --- args ---
for arg in "$@"; do
  case "$arg" in
    -release)
      common_flags=("${release_flags[@]}")
      build_steps=("${prod_steps[@]}")
      ;;
    *)
      die "Unknown parameter: \"$arg\""
      ;;
  esac
done

printf '%sUsing compiler flags:%s ' "$bold_white" "$end"
printf '%q ' "${compiler_defines[@]}" "${common_flags[@]}"
printf '\n'

need_cmd odin

# --- build dir handling ---
mkdir -p bin
orig_dir=$PWD
trap 'cd "$orig_dir" >/dev/null 2>&1 || true' EXIT
cd bin

# --- steps ---
for step in "${build_steps[@]}"; do
  case "$step" in
    test)
      printf '\n%sRunning tests%s\n' "$bold_white" "$end"
      if ! run odin test ../src -collection:lib=../lib "${compiler_defines[@]}" "${common_flags[@]}"; then
        die "FAIL"
      fi
      if ! run odin test ../lib/tests -all-packages -collection:lib=../lib "${compiler_defines[@]}" "${common_flags[@]}"; then
        die "FAIL"
      fi
      printf '\n'
      ;;

    build)
      printf '%sBuilding:%s %s/%s\n' "$bold_white" "$end" "$PWD" "$bin_name"
      if ! run odin build ../src -collection:lib=../lib  -out:"$bin_name" -show-timings "${compiler_defines[@]}" "${common_flags[@]}"; then
        die "FAIL"
      fi
      printf '\n%sOK%s\n\n' "$bold_green" "$end"
      ;;

    strip)
      need_cmd strip
      run strip -s "$PWD/$bin_name"
      ;;

    *)
      ;;
  esac
done