#!/bin/bash
# Repackage MRIcron upstream sources. Determine version, strip unnecessary
# files, zip->tar.gz
#
# Usage:
#   repack.sh <mricron.zip>
#

set -e

ORIGSRC=$1
if [ -z "$ORIGSRC" ]; then
	echo "No upstream sources given."
	exit 1
fi

CURDIR=$(pwd)
WDIR=$(mktemp -d)
SUBDIR=mricron

# put upstream sources into working dir
ORIGSRC_PATH=$(readlink -f ${ORIGSRC})
cd $WDIR
unzip $ORIGSRC_PATH

UPSTREAM_VERSION=$(date --date "$(grep 'kMRIcronVersDate.*=' \
					< $SUBDIR/common/define_types.pas \
					| cut -d "'" -f 2,2)" +0.%Y%m%d.1)
ORIG_VERSION="$UPSTREAM_VERSION~dfsg.1"

echo "Determined version: $UPSTREAM_VERSION"
echo "Debian orig version: $ORIG_VERSION"

# cleanup
# leftovers from previous compile runs
find $SUBDIR -name '*.o' -delete -o -name '*.ppu' -delete
find $SUBDIR -name '*.compiled' -delete
find $SUBDIR -name '*.exe' -delete
find $SUBDIR -name '*.or' -delete
rm -f $SUBDIR/mricron.rc
rm -f $SUBDIR/mricron.lrs
rm -f $SUBDIR/mricron
rm -f $SUBDIR/dcm2nii/dcm2nii
rm -f $SUBDIR/dcm2nii/dcm2niigui
rm -f $SUBDIR/npm/npm
rm -fr "$SUBDIR/New Folder"

# other unnecessary pieces
find $SUBDIR -name '*~' -delete
find $SUBDIR -name '*.bak' -delete
find $SUBDIR -iname "Thumbs.db" -delete
find $SUBDIR -iname .DS_Store  -delete
find $SUBDIR -type d -iname backup -delete

# no delphi on Debian
rm -rf $SUBDIR/delphionly

mv $SUBDIR mricron-$ORIG_VERSION.orig
tar czf mricron_$ORIG_VERSION.orig.tar.gz mricron-$ORIG_VERSION.orig
mv mricron_$ORIG_VERSION.orig.tar.gz $CURDIR

# clean working dir
rm -rf $WDIR

echo "Tarball is at: $CURDIR/mricron_$ORIG_VERSION.orig.tar.gz"

