#!/bin/sh

[ -z $PREPKG ] && exit 1

PACKAGE=yamagi-quake2
QVERSION=6.00
CVERSION=1.04
RVERSION=2.03
XVERSION=2.04
FILES=$(cd $(dirname $0) ; pwd)

mkdir -p \
  $PREPKG/{install,usr/{doc/$PACKAGE-{$QVERSION,ctf-$CVERSION,rogue-$RVERSION,xatrix-$XVERSION},games,share/{applications,games/$PACKAGE/{ctf,xatrix,rogue},pixmaps}}}/

# extract everything at once
for i in \
quake2-$QVERSION.tar.xz \
quake2-ctf-$CVERSION.tar.xz \
quake2-rogue-$RVERSION.tar.xz \
quake2-xatrix-$XVERSION.tar.xz ; do
  tar xf $FILES/$i || exit 1
done

chmod -R \
  go+r .
chown -R \
  root:root .

# base
cd quake2-$QVERSION/
make $MAKEJOBS \
  WITH_SYSTEMWIDE=yes \
  WITH_SYSTEMDIR=/usr/share/games/$PACKAGE &> make.output || exit 1
cp -a \
  release/* \
  $PREPKG/usr/share/games/$PACKAGE/
cp -p \
  stuff/icon/Quake2.png \
  $PREPKG/usr/share/pixmaps/
cp -p \
  CHANGELOG CONTRIBUTE LICENSE README.md \
  stuff/README.old stuff/cdripper.sh stuff/yq2.cfg \
  $PREPKG/usr/doc/$PACKAGE-$QVERSION/
cd -

# threewave ctf
cd quake2-ctf-$CVERSION/
make $MAKEJOBS &> make.output || exit 1
cp -p \
  release/game.so \
  $PREPKG/usr/share/games/$PACKAGE/ctf/
cp -p \
  CHANGELOG LICENSE README \
  $PREPKG/usr/doc/$PACKAGE-ctf-$CVERSION/
cd -

# missionpack 2 (ground zero)
cd quake2-rogue-$RVERSION/
make $MAKEJOBS &> make.output || exit 1
cp -p \
  release/game.so \
  $PREPKG/usr/share/games/$PACKAGE/rogue/
cp -p \
  CHANGELOG LICENSE README \
  $PREPKG/usr/doc/$PACKAGE-rogue-$RVERSION/
cd -

# missionpack 1 (the reckoning)
cd quake2-xatrix-$XVERSION/
make $MAKEJOBS &> make.output || exit 1
cp -p \
  release/game.so \
  $PREPKG/usr/share/games/$PACKAGE/xatrix/
cp -p \
  CHANGELOG LICENSE README \
  $PREPKG/usr/doc/$PACKAGE-xatrix-$XVERSION/
cd -

# misc stuff
for i in \
$PACKAGE \
$PACKAGE-ctf \
$PACKAGE-rogue \
$PACKAGE-xatrix ; do
  cp \
    $FILES/$i.sh \
    $PREPKG/usr/games/$i
  chmod +x \
    $PREPKG/usr/games/$i
done

cp \
  $FILES/$PACKAGE.desktop \
  $PREPKG/usr/share/applications/

cp \
  $FILES/{doinst.sh,slack-desc} \
  $PREPKG/install/

find $PREPKG -exec file {} \; \
  | awk -F : '/ ELF / {print $1}' \
  | xargs strip -p --strip-unneeded
