#!/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
    cp -r extra/* bin/
    typeset -i build_number=$(cat other/build.nr)
    ((build_number++))
    truncate -s 0 other/build.nr
    echo $build_number >> other/build.nr
# elif [[ "$1" == "windows_release" ]]; then
#     cd other
#     chmod +x build_windows_release.sh
#     ./build_windows_release.sh
#     cd ../bin/DragonV2_w64
#     cd ../..
# elif [[ "$1" == "linux_release" ]]; then
#     cd other
#     chmod +x build_linux_release.sh
#     ./build_linux_release.sh
#     cd ../bin/DragonV2_linux64
#     cd ../..
# elif [[ "$1" == "dependencies" ]]; then
#     cd other
#     chmod +x build_dependencies.sh
#     ./build_dependencies.sh
#     cd ..
else
    cp -r extra/* 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 Application...\n\n\033[0m"
     	cd bin
        ./pianolib
        cd ..
	elif [[ "$1" == "gdb" ]]; then
	    printf "\n\033[0;32mDebugging Application...\n\n\033[0m"
	    cd bin
  		gdb -batch \
		    -ex 'set pagination off' \
		    -ex 'set print pretty on' \
		    -ex 'set logging file gdb-last.log' \
		    -ex 'set logging overwrite on' \
		    -ex 'set logging on' \
		    -ex 'handle SIGPIPE nostop noprint pass' \
		    -ex run \
		    -ex 'bt full' \
		    -ex 'info locals' \
		    -ex 'info args' \
		    -ex quit \
	        --args ./pianolib
	    cd ..
    fi
fi
