#!/bin/bash
# Repackage EEGLAB upstream sources, strip unnecessary files, and convert zip
# into tar.gz archive.
#
# Usage:
#   repack_upstream --upstream-version <version> <eeglab.zip>
#

set -e

SANITYCHECK=$1
UVER=$2
ORIGSRC=$3

if [ ! "$SANITYCHECK" = "--upstream-version" ]; then
	echo "This script should be called: repack_upstream --upstream-version <version> <eeglab.zip>"
	exit 1
fi

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

CURDIR=$(pwd)
WDIR=$(mktemp -d)
MAJORVERSION="$(echo ${UVER} | cut -d . -f 1,1)"
PACKAGENAME=eeglab${MAJORVERSION}
SUBDIR=${PACKAGENAME}-${UVER}.orig
# tildify version extensions: 0.1.1beta -> 0.1.1~beta
UVER=$(echo $UVER | sed -e 's/\(.*\)\([a-zA-Z]\+\)/\1~\2/g')

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

mv eeglab* ${SUBDIR}

# cleanup
# remove all external toolboxes with lots of source-less binaries
find ${SUBDIR}/external -mindepth 1 -maxdepth 1 -type d -exec rm -rf {} \;
# remove source-less java stuff
rm -rf ${SUBDIR}/functions/javachatfunc
# another source-less blob
rm -f ${SUBDIR}/functions/resources/ica_linux
# get rid of all plugins that ship with binaries (maybe removing a bit much
# here)
rm -rf ${SUBDIR}/plugins/anteepimport*
rm -rf ${SUBDIR}/plugins/bci2000import*
rm -rf ${SUBDIR}/plugins/erpssimport*
rm -rf ${SUBDIR}/plugins/fmrib*
# catch all missing binary extensions
find ${SUBDIR} -name '*.mex*' -delete
# strip compiled manuals
find ${SUBDIR} -name '*.pdf' -delete

# therefore we are going to use the latest modification date of any file in the
# sources
UPSTREAM_VERSION=$(grep '^% Version' ${SUBDIR}/Contents.m | cut -d ' ' -f3,3 | sed -e 's/\(.*\)\([a-zA-Z]\+\)/\1~\2/g')

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

tar czf ${PACKAGENAME}_${UVER}.orig.tar.gz ${SUBDIR}
mv ${PACKAGENAME}_${UVER}.orig.tar.gz $CURDIR

# clean working dir
rm -rf $WDIR

echo "Tarball is at: $CURDIR/${PACKAGENAME}_${UVER}~dfsg.1.orig.tar.gz"

