#!/bin/bash
#Xash3d old engine compile script for Intel Mac OS X 10.4 Tiger by Alex Free

version=r2
set -e
cd "$(dirname "$0")"

if [[ $EUID -ne 0 ]]; then
   echo "Execute sudo "$0". The user $USER does not have the privileges necessary to continue." 
   exit 1
fi

rm -rf /Applications/Half-Life.app
cp -r Half-Life.app /Applications
cp applet.icns /Applications/Half-Life.app/Contents/Resources/
sudo port -d install libsdl2 gcc6 git binutils
if [ ! -d "xash3d" ]; then
	git clone --recursive https://github.com/alex-free/xash3d
fi
if [ ! -d "hlsdk-xash3d" ]; then
	git clone --recursive https://github.com/alex-free/hlsdk-xash3d
fi
sudo port select --set gcc mp-gcc6
cd xash3d
rm -rf build
mkdir build
cd build
cmake -DCMAKE_OBJCOPY=/opt/local/bin/gobjcopy -DCMAKE_C_COMPILER=/opt/local/bin/gcc -DCMAKE_CXX_COMPILER=/opt/local/bin/g++ -DXASH_SDL=yes -DXASH_VGUI=NO -DCMAKE_INSTALL_PREFIX=/Applications/Half-Life.app -DXASH_SINGLE_BINARY=YES -DXASH_STATIC=yes -DCMAKE_C_FLAGS="-static-libstdc++ -static-libgcc" ../
make install
cd ../../
rm -rf xash3d/build
cd hlsdk-xash3d
rm -rf build
mkdir build
cd build
cmake -DCMAKE_OBJCOPY=/opt/local/bin/gobjcopy -DCMAKE_C_COMPILER=/opt/local/bin/gcc -DCMAKE_CXX_COMPILER=/opt/local/bin/g++ -DGOLDSOURCE_SUPPORT=ON -DCMAKE_C_FLAGS="-static-libstdc++ -static-libgcc" -DCMAKE_INSTALL_PREFIX=/Applications/Half-Life.app/lib/xash3d ../
make install
cd ../../
rm -rf hlsdk-xash3d/build

#libsdl2 dylib
cp /opt/local/lib/libSDL2-2.0.0.dylib /Applications/Half-Life.app/lib/xash3d/
install_name_tool -change /opt/local/lib/libSDL2-2.0.0.dylib @executable_path/libSDL2-2.0.0.dylib /Applications/Half-Life.app/lib/xash3d/libSDL2-2.0.0.dylib
#libsdl2 linked
install_name_tool -change /opt/local/lib/libSDL2-2.0.0.dylib @executable_path/libSDL2-2.0.0.dylib /Applications/Half-Life.app/lib/xash3d/xash3d
#client dylib
install_name_tool -change /usr/local/valve/cl_dlls/client.dylib @executable_path/valve/cl_dlls/client.dylib /Applications/Half-Life.app/lib/xash3d/valve/cl_dlls/client.dylib
#hl dylib
install_name_tool -change /usr/local/valve/dlls/hl.dylib @executable_path/valve/dlls/hl.dylib /Applications/Half-Life.app/lib/xash3d/valve/dlls/hl.dylib

mkdir -p /Applications/Half-Life.app/lib/xash3d/valve
chmod -R 777 /Applications/Half-Life.app
rm -rf xash3d-tiger-"$version"-i386
mkdir xash3d-tiger-"$version"-i386
cp readme.html xash3d-tiger-"$version"-i386
cp -r licenses xash3d-tiger-"$version"-i386
cp -r /Applications/Half-Life.app xash3d-tiger-"$version"-i386/
