#!/bin/bash

# Build a Twin Dragon td.grp file from the contents of the original Shadow
# Warrior sw.grp and the resources from the Twin Dragon .zip download
# file. Uses kextract and kgroup, which in my case came from eduke32.

# The "source" files for this:
# sw.grp from the Shadow Warrior 1.2 CD, md5sum
# 9d200b5fb4ace8797e7f8638c4f96af2
# tdragon.zip from https://image.dosgamesarchive.com/games/tdragon.zip,
# md5sum ccf9468d0aa6534f2c077e09ab50c94a

set -e

EXPECT_CRC="e06cb6b4"

CWD="$(pwd)"

SWGRP="${1:-/usr/share/games/jfsw/sw_registered.grp}"
TDZIP="${2:-$CWD/tdragon.zip}"
TDGRP="${3:-$CWD/td.grp}"

rm -rf tmp doc
mkdir -p tmp/sw tmp/td doc

# extract the original data
cd $CWD/tmp/sw
kextract "$SWGRP" '*'

# extract the mod
cd $CWD/tmp/td
unzip "$TDZIP"

# keep the docs
mv *.doc *.txt $CWD/doc

# ditch the executables
rm -rf *.exe *.bat

# Not sure what LOADER.IAF is, but it doesn't hurt anything to leave it
# in the .grp file.

# uppercase all the filenames
for file in *; do
  upper="$( echo "$file" | tr a-z A-Z )"
  [ "$file" != "$upper" ] && mv "$file" "$upper"
done

# overwrite same-named stuff in the original with the mods
mv * $CWD/tmp/sw
cd $CWD/tmp/sw
kgroup $CWD/td.grp *

cd $CWD

# kgroup insists on creating files with mode 0600...
chmod 644 td.grp

# make the release zip file
zip -j jfsw_twin_dragon-$( date +%Y%m%d ).zip \
  td.grp TDchallenge.html doc/* README.txt mkgrp.sh *.diff

# this is a dumb way to calculate the crc32 but it uses stuff
# you should already have installed.
echo
echo "Checking td.grp CRC32"
rm -f tmp.zip
zip tmp.zip td.grp
CRC="$( zipinfo -v tmp.zip | grep CRC | sed 's,.*  ,,' )"
echo
echo -n "CRC32 is 0x$CRC, "
if [ "$CRC" = "$EXPECT_CRC" ]; then
  echo "OK"
else
  echo "does not match expected 0x$EXPECT_CRC!"
fi

rm -f tmp.zip
md5sum td.grp
