#!/bin/sh

# build_darkplaces.rpi3.sh
# 2017-11-21
# by Gernot Walzl

# Downloads, builds and installs darkplaces (Quake) on Raspbian.

# SDL2 needs to be built with a video driver that supports
# hardware-accelerated graphics rendering.

# Based on the following post:
# https://www.raspberrypi.org/forums/viewtopic.php?f=78&t=72301&start=100

SOURCE="darkplaces-rpi.zip"
DOWNLOAD="https://github.com/joolswills/darkplaces/archive/rpi.zip"
DEPENDS="build-essential libjpeg-dev xterm"
DEST="/usr/local/games/quake"

# 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 darkplaces-rpi
chown -R root:root .

# build
case "$(cat /proc/device-tree/model)" in
  'Raspberry Pi 3'*)
    RPICFLAGS="-mcpu=cortex-a53 -mfpu=neon-fp-armv8 -mfloat-abi=hard -funsafe-math-optimizations"
    ;;
  'Raspberry Pi 2'*)
    RPICFLAGS="-mcpu=cortex-a7 -mfpu=neon-vfpv4 -mfloat-abi=hard -funsafe-math-optimizations"
    ;;
  *)
    echo 'Error: Unable to determine Raspberry Pi board version.'
    exit 1
esac
CFLAGS="$RPICFLAGS" make sdl-release DP_MAKE_TARGET=rpi
CFLAGS="$RPICFLAGS" make sv-release DP_MAKE_TARGET=rpi

# install
install -m 0644 darkplaces32x32.png /usr/share/pixmaps
mkdir -p "$DEST/id1"
install -m 0755 darkplaces-sdl "$DEST"
install -m 0755 darkplaces-dedicated "$DEST"

# launcher
cat > '/usr/local/games/darkplaces' <<EOF
#!/bin/sh
export SDL_VIDEODRIVER='rpi'
cd $DEST
./darkplaces-sdl "\$@"
EOF
chmod +x '/usr/local/games/darkplaces'
cat > '/usr/share/applications/darkplaces.desktop' <<EOF
[Desktop Entry]
Type=Application
Name=darkplaces
Exec=xterm -fullscreen -e darkplaces
Icon=darkplaces32x32
Terminal=false
Categories=Game;
EOF

# required files
cat > "$DEST/id1/CHECKSUMS.md5" <<EOF
5906e5998fc3d896ddaf5e6a62e03abb  pak0.pak
d76b3e5678f0b64ac74ce5e340e6a685  pak1.pak
EOF