#!/bin/bash

# Colors
RED="\033[0;31m"
BOLD="\033[1m"
NC="\033[0m" # No Color

BUILD_TYPE="Debug"
ACCEPTED_BUILD_TYPES=("Debug" "RelWithDebInfo" "Release")
KERNEL="$(uname -s)"
ARGS=""

join_array_elements() {
  local IFS=","
  echo "$*"
}

contains() {
  local item="$1"; shift
  local e
  for e; do
    [[ "$e" == "$item" ]] && return 0
  done
  return 1
}

print_usage() {
  echo -e "Usage: build [-b build_type] ..."
  echo -e "  Options:"
  echo -e "    -b, --build-type    Choose from $(join_array_elements ${ACCEPTED_BUILD_TYPES[*]}) (Default: Debug)."
  echo -e "    -h, --help          Print this message and exit"
}

while [[ $# > 0 ]];do
  case $1 in
    -b|--build-type)
      BUILD_TYPE="$2"
      shift 2
      ;;
    -h|--help)
      print_usage
      exit 0
      ;;
    *|-*|--*)
      rest=("$@")
      ARGS+=" ${rest[0]}"
      shift
      ;;
  esac
done

if ! contains ${BUILD_TYPE} "${ACCEPTED_BUILD_TYPES[@]}"; then
  echo -e "${RED}${BOLD}Unknown build type: ${BUILD_TYPE}${NC}\n"
  print_usage
  exit 1
fi

bear -- make BUILD_TYPE=$BUILD_TYPE $ARGS
