#!/bin/sh

set -e

if [ -e README.Debian ] ; then 
  cd ..
fi

uscan --report --dehs . > /tmp/uscan.out|| true

UPSTREAM_VERSION=`grep '<upstream-version>' /tmp/uscan.out| sed 's#</\?upstream-version>##g'`
UPSTREAM_URL=`grep '<upstream-url>' /tmp/uscan.out| sed 's#</\?upstream-url>##g'`

UPSTREAM_TARBALL=frogatto-$UPSTREAM_VERSION.tar.gz
DEBIAN_VERSION=`dpkg-parsechangelog \
    | grep ^Version \
    | awk '{print $2}' \
    | sed 's/-[[:digit:]]\+$//'`

FROGATTO_TARBALL=frogatto_$DEBIAN_VERSION.orig.tar.gz
FROGATTO_DATA_TARBALL=frogatto-data_$DEBIAN_VERSION.orig.tar.gz

echo UPSTREAM_VERSION=$UPSTREAM_VERSION
echo UPSTREAM_URL=$UPSTREAM_URL
echo UPSTREAM_TARBALL=$UPSTREAM_TARBALL
echo DEBIAN_VERSION=$DEBIAN_VERSION
echo FROGATTO_TARBALL=$FROGATTO_TARBALL
echo FROGATTO_DATA_TARBALL=$FROGATTO_DATA_TARBALL

if ! test -f ../$UPSTREAM_TARBALL; then
    if ! wget --output-document=../$UPSTREAM_TARBALL $UPSTREAM_URL; then
    	echo "Error downloading upstream tarball"
    	exit -1
    fi
fi

TEMP_DIR=`mktemp -d /tmp/frogatto-tgz.XXXXXXXXX`
SRC_DIR=$TEMP_DIR/frogatto-$UPSTREAM_VERSION
FROGATTO_DIR=$TEMP_DIR/frogatto-$DEBIAN_VERSION
FROGATTO_DATA_DIR=$TEMP_DIR/frogatto-data-$DEBIAN_VERSION

trap "rm -fr $TEMP_DIR" INT
echo "Use temporary directory $TEMP_DIR"

echo -n "Unpacking tarball... "
if tar -xf `pwd`/../$UPSTREAM_TARBALL -C $TEMP_DIR; then
    find $TEMP_DIR -type d -exec chmod 0755 '{}' +
    find $TEMP_DIR -type f -exec chmod 0644 '{}' +
    echo done
else
    echo fail
    rm -fr $TEMP_DIR
    exit 2
fi

#echo -n "Patching Makefile..."
#perl -pi -e 's/^(\s*)ccache\s+/$1/g' $SRC_DIR/Makefile 
#echo done

echo "Clean tree... "
rm -r $SRC_DIR/DejaVuSans.ttf \
    $SRC_DIR/FreeMono.ttf \
    $SRC_DIR/Ubuntu*.ttf \
    $SRC_DIR/Makefile?* \
    $SRC_DIR/android \
    $SRC_DIR/MacOS*
find $SRC_DIR -name "music_aac" |xargs rm -r
find $SRC_DIR -name "music_aac_mini" |xargs rm -r
find $SRC_DIR -name "sounds_wav" |xargs rm -r
echo done
    
echo -n "Kill all modules of assets but frogatto..."    
( cd $SRC_DIR/modules ; rm -r `ls | grep -v frogatto ` )
for n in cellular civ ct rpg ; do
  rm $SRC_DIR/$n
done
echo done

mkdir -v $FROGATTO_DIR $FROGATTO_DATA_DIR

echo -n "Split data in directories... "

cp $SRC_DIR/INSTALL $FROGATTO_DIR
cp $SRC_DIR/LICENSE $FROGATTO_DIR
cp $SRC_DIR/modules/frogatto/CHANGELOG $FROGATTO_DIR
mv $SRC_DIR/Makefile $FROGATTO_DIR
mv $SRC_DIR/src $FROGATTO_DIR

mv $SRC_DIR/* $FROGATTO_DATA_DIR/
echo done

echo -n "Packing frogatto ($FROGATTO_TARBALL)... "
tar -C $TEMP_DIR -czf `pwd`/../$FROGATTO_TARBALL frogatto-$DEBIAN_VERSION
echo done
echo -n "Packing frogatto-data ($FROGATTO_DATA_TARBALL)... "
tar -C $TEMP_DIR -czf `pwd`/../$FROGATTO_DATA_TARBALL frogatto-data-$DEBIAN_VERSION    
echo done
exec rm -fr $TEMP_DIR /tmp/uscan.out
