#!/bin/sh
MY_PATH="$(dirname "$0")"
APP_NAME="Carmageddon"
ICON_FILE="icon.png"
cd "${MY_PATH}" || exit 1
# cleanup
rm -rf .build
rm -rf "${APP_NAME}.$(uname)-$(uname -m)"
# compiler and linker flags to use
CPPFLAGS="-DDETHRACE_FIX_BUGS=1 -Isrc/harness/include -Isrc/harness -Isrc/smackw32/include -Isrc/BRSRC13/include -Isrc/BRSRC13 -Isrc/S3/include -Isrc/S3 -Isrc/DETHRACE/common -Isrc/DETHRACE/pd -Isrc/DETHRACE -Ilib/glad/include -Ilib/libsmacker -Ilib/miniaudio/include -Ilib/miniaudio/include/miniaudio -Ilib/SDL2 -Ilib"
# read the source files list from the Visual Studio project file if it exists, else list all the .c files from "lib" and "src"
if [ -f "${APP_NAME}.vcxproj" ]; then
SRCLIST="$(grep "<ClCompile " ${APP_NAME}.vcxproj|awk -F\" '{print $2}'|tr '\\' '/')"
else
SRCLIST="$(find lib -name '*.c') $(find src -name '*.c')"
fi
# generate the shader programs
echo "Compacting GLSL shaders..."
cd src/harness || exit 1
for SHADER in resources/*.glsl; do
echo "${SHADER}"
SYMBOL_NAME="$(echo "${SHADER}"|tr '[:lower:]' '[:upper:]'|sed 's/[\.\/]/_/g')"
(
echo "// Auto generated file."
echo "static const char ${SYMBOL_NAME}[] ="
echo "{"
cat "${SHADER}"|hexdump -e '16/1 "%02x" "\n"' -v|sed 's/[0-9a-fA-F][0-9a-fA-F]/0x&, /g' || exit 1
echo "};"
) > "${SHADER}.h"
done
cd ../..
# target the current arch only
for ARCH in $(uname -m); do
echo "Compiling for ${ARCH}..."
rm -rf ".build/${ARCH}"
mkdir -p ".build/${ARCH}" || exit 1
# compile source files
for SRCFILE in ${SRCLIST}; do
echo "${SRCFILE}"
cc -o ".build/${ARCH}/$(basename "${SRCFILE}").o" ${CPPFLAGS} -c "${SRCFILE}" || exit 1
done
# link them together
echo "Linking for ${ARCH}..."
cc -o ".build/${ARCH}/${APP_NAME}" ".build/${ARCH}/"*".o" /usr/local/lib/libSDL2.a /usr/local/lib/libinotify.a -lusbhid -lpthread -lm -lexecinfo || exit 1
done
# retrieve the compiled executable
cp ".build/${ARCH}/${APP_NAME}" "${APP_NAME}.$(uname)-$(uname -m)"
# finished
echo "Carmageddon was built successfully"
exit 0