#!/bin/bash
set -eo pipefail

SUCCESS_TXT="${GREEN}[SUCCESS]${NC}"

src_file=$1
exe_file=$(basename "${src_file%.*}")

if [[ -z "$MACHINE" ]]; then
  echo "Must provide MACHINE for compile"
  exit 1
fi

if [[ "$MACHINE" == "Windows" ]]; then
  exe_file=$(basename "${src_file%.*}".exe)
fi

if [[ -z "$src_file" ]]; then
  echo "Must provide \$1 for compile"
  exit 1
fi

if [[ -z "$CPP_INCLUDE_DIR" ]]; then
  echo "Must provide CPP_INCLUDE_DIR in environment"
  exit 1
fi

if [[ -z "$CPP" ]]; then
  echo "Must provide CPP in environment"
  exit 1
fi

rm -f "$exe_file"

EXTRA_ARGS=""
if [[ "$CPP" == "clang++" && "$MACHINE" == "Windows" ]]; then
  msvc_version="2022"
  wk_version="10.0.19041.0"
  EXTRA_ARGS=" -I\"$TESTS_DIR/lib/msvc-$msvc_version-include\""
  for s in cppwinrt shared ucrt um winrt; do
    EXTRA_ARGS="$EXTRA_ARGS -I\"$TESTS_DIR/lib/windows-kit-$wk_version-include/$s\""
  done
fi

if [[ "$CPP" == "cl.exe" ]]; then
  echo "Compiling $src_file, running:" "$CPP" "$CPP_STANDARD" "-F268435456" "-EHsc" "-O2" -I"${CPP_INCLUDE_DIR}" -Fe"$exe_file" "$src_file"
  "$CPP" "$CPP_STANDARD" "-F268435456" "-EHsc" "-O2" -I"${CPP_INCLUDE_DIR}" -Fe"$exe_file" "$src_file" &>/dev/null
else
  "$CPP" -v
  echo "Compiling $src_file, running:" "$CPP" "$CPP_OPTS" "$CPP_STANDARD" -Wpedantic -Werror -I"${CPP_INCLUDE_DIR}""$EXTRA_ARGS" -o"$exe_file" -O2 "$src_file"
  dir=$(dirname "$CPP")
  OLD_PATH="$PATH"
  if [[ "$dir" == *"/bin" ]]; then
    export PATH="$dir":$PATH
    EXTRA_ARGS="${EXTRA_ARGS} -static"
  fi
  eval "$CPP" "$CPP_OPTS" "$CPP_STANDARD" -Wpedantic -Werror -I"${CPP_INCLUDE_DIR}""$EXTRA_ARGS" -o"$exe_file" -O2 "$src_file"
  export PATH="$OLD_PATH"
fi

rm -f ./*.o ./*.obj

if [ ! -f "$exe_file" ]; then
  echo "Compilation failed: file $exe_file not found"
  exit 1
fi

echo -e "${SUCCESS_TXT} $src_file compiled\n"

if [[ "$2" == "--check-only" ]]; then
  rm -rf "$exe_file"
fi
