#!/bin/sh

# build_quake3.rpi3.sh
# 2019-12-29
# by Gernot Walzl

# Downloads, builds and installs Quake 3 on Raspbian.

# If libEGL.so or libGLESv2.so is missing,
# run rpi-update and reboot.
# If the sound quality is low (crackling noises) in Raspbian 10 (buster)
# and you have pulseaudio installed, add tsched=0 in /etc/pulse/default.pa:
# load-module module-udev-detect tsched=0

SOURCE="quake3-master.zip"
DOWNLOAD="https://github.com/raspberrypi/quake3/archive/master.zip"
DEPENDS="build-essential libsdl-dev"
DEST="/usr/local/games/quake3"

# exit on error
set -e

# install dependencies
apt-get install $DEPENDS

# download
if [ ! -f "$SOURCE" ]; then
  wget -O "$SOURCE" "$DOWNLOAD"
fi

# extract
unzip "$SOURCE"
cd quake3-master
chown -R root:root .

# build
sed -i 's/-lvmcs_rpc_client //' build_rpi_raspbian.sh
./build_rpi_raspbian.sh

# install
sed 's/Terminal=false/Terminal=true/' misc/setup/ioquake3.desktop \
  > /usr/share/applications/ioquake3.desktop
install -m 0644 misc/quake3.png /usr/share/pixmaps
cd build/release-linux-arm
mkdir -p "$DEST/baseq3"
mkdir -p "$DEST/missionpack"
install -m 0755 ioq3ded.arm ioquake3.arm "$DEST"
install -m 0755 baseq3/*.so "$DEST/baseq3"
install -m 0755 missionpack/*.so "$DEST/missionpack"

# launcher
cat > '/usr/local/games/ioquake3' <<EOF
#!/bin/sh
cd $DEST
./ioquake3.arm "\$@"
EOF
chmod +x '/usr/local/games/ioquake3'

# required files
cat > "$DEST/baseq3/CHECKSUMS.md5" <<EOF
1197ca3df1e65f3c380f8abc10ca43bf  pak0.pk3
48911719d91be25adb957f2d325db4a0  pak1.pk3
d550ce896130c47166ca44b53f8a670a  pak2.pk3
968dfd0f30dad67056115c8e92344ddc  pak3.pk3
24bb1f4fcabd95f6e320c0e2f62f19ca  pak4.pk3
734dcd06d2cbc7a16432ff6697f1c5ba  pak5.pk3
873888a73055c023f6c38b8ca3f2ce05  pak6.pk3
8fd38c53ed814b64f6ab03b5290965e4  pak7.pk3
d8b96d429ca4a9c289071cb7e77e14d2  pak8.pk3
EOF
cat > "$DEST/missionpack/CHECKSUMS.md5" <<EOF
e8ba9e3bf06210930bc0e7fdbcdd01c2  pak0.pk3
8b8a51f9edf2671dfeb53e0405bac3c6  pak1.pk3
4e02be54614ca7dbed81b5c44a19302d  pak2.pk3
e7f91f4eb6e3d28d978b8cca54631695  pak3.pk3
EOF