#!/bin/sh

# Repackage upstream source to exclude precompiled binary MicroPython
# firmware, which is included both as a flashable file and as a hex
# string in uflash.py
#
# Repack script adapted from that included with ruby-fakeweb.
#
# Should be called as "repack.sh --upstream-source <ver> <downloaded file>
# (for example, via uscan using a v3 debian/watch file)

set -e
set -u

VER="$2+dfsg"
FILE="$3"
PKG=`dpkg-parsechangelog|grep ^Source:|sed 's/^Source: //'`

REPACK_DIR="$PKG-$VER.orig" # DevRef § 6.7.8.2
DEST_DIR=$(dirname "$FILE")

echo -e "\nRepackaging $FILE\n"

DIR=`mktemp -d ./tmpRepackXXXXXX`
trap "rm -rf \"$DIR\"" QUIT INT EXIT

# Create an extra directory to cope with rootless tarballs
UP_BASE="$DIR/unpack"
mkdir "$UP_BASE"
tar xzf "$FILE" -C "$UP_BASE"

if [ `ls -1 "$UP_BASE" | wc -l` -eq 1 ]; then
    # Tarball does contain a root directory
    UP_BASE="$UP_BASE/`ls -1 "$UP_BASE"`"
fi

## Remove git/CI configs
rm -fv  "$UP_BASE/.gitignore" 2>/dev/null
rm -fv  "$UP_BASE/.travis.yml" 2>/dev/null
## Remove Windows build scripts
rm -fv "$UP_BASE/docs/make.bat" 2>/dev/null
## Remove firmware hex file
rm -fv  "$UP_BASE/firmware.hex" 2>/dev/null
## Remove hex string from uflash.py
awk '/^_RUNTIME/,/^"""/{next}1' "$UP_BASE/uflash.py" >"$UP_BASE/uflash-patched.py" \
    && mv "$UP_BASE/uflash-patched.py" "$UP_BASE/uflash.py"
## End

mv "$UP_BASE" "$DIR/$REPACK_DIR"

# Using a pipe hides tar errors!
tar cfC "$DIR/repacked.tar" "$DIR" "$REPACK_DIR"
gzip -9 < "$DIR/repacked.tar" > "$DIR/repacked.tar.gz"
FILE="${DEST_DIR}/${PKG}_${VER}.orig.tar.gz"
mv "$DIR/repacked.tar.gz" "$FILE"

echo "*** $FILE repackaged"
