#!/bin/bash

set -e

MAKE_COMMAND=make
MAKEFILE_TYPE="Unix Makefiles"

if [[ "$(uname)" == "Darwin" ]]; then
	NJOBS=-j"$(sysctl -n hw.ncpu)"
else
	NJOBS=-j$(nproc)
fi

if [[ "$(uname -s)" == MINGW64_NT* ]]; then
    MAKE_COMMAND=mingw32-make.exe
    MAKEFILE_TYPE="MinGW Makefiles"
fi

if [[ "$1" == "debug" || "$1" == "release" ]]; then
    BUILD_TYPE="$(tr '[:lower:]' '[:upper:]' <<< ${1:0:1})${1:1}"
    rm -rf bin
    cmake -B bin -S ./ -G "$MAKEFILE_TYPE" -DCMAKE_BUILD_TYPE=$BUILD_TYPE
    $MAKE_COMMAND -C bin $NJOBS --no-print-directory
    find extra -mindepth 1 -maxdepth 1 -exec cp -r {} bin/ \;
    build_number=$(cat other/build.nr)
    build_number=$((build_number + 1))
    truncate -s 0 other/build.nr
    echo $build_number >> other/build.nr
    cd other
    ./create_release.sh
    cd ..
elif [[ "$1" == "install" ]]; then
	cd other
    ./install_release.sh
    cd ..
else
    find extra -mindepth 1 -maxdepth 1 -exec cp -r {} bin/ \;
    printf "\n\033[0;32mBuilding Changes...\n\n\033[0m"
    $MAKE_COMMAND -C bin $NJOBS --no-print-directory
    if [[ "$1" == "run" ]]; then
        printf "\n\033[0;32mRunning Test Application...\n\n\033[0m"
        cd bin
        ./ostd_test
        cd ..
    fi
fi
