#!/bin/sh

set -e

PKG_NAME="$(dpkg-parsechangelog | awk '/^Source:/ {print $2}')"
UP_VERSION="$(dpkg-parsechangelog | \
    awk '/^Version:/ {gsub(/\.dfsg.*/, "", $2); print $2}')"
DFSG="$(shell dpkg-parsechangelog | \
    awk '/^Version:/ {gsub(/.*.dfsg/, ".dfsg", $2); gsub(/-.*/, "", $2); print $2}')"
ORIG_DIR="$PKG_NAME-$UP_VERSION$DFSG.orig"
ORIG_NAME="${PKG_NAME}_$UP_VERSION$DFSG.orig"
UP_DIR="$(pwd)/../tarballs"
UP_SITE="https://meyerweb.com/eric/tools/s5/v/$UP_VERSION/"
UP_DISTVER="$(printf -- '%s' "$UP_VERSION" | tr -d '.')"
UP_DISTNAME="$PKG_NAME-$UP_DISTVER"
UP_TARBALL="$UP_DISTNAME.zip"
BLANKFILE="$UP_DIR/$UP_DISTNAME/s5-blank.zip"
RM_FILES='ui/i18n'

# Fetch the upstream tarball if needed
echo "up $UP_TARBALL site $UP_SITE orig $ORIG_NAME"
mkdir -p -- "$UP_DIR"
if [ ! -f "$UP_DIR/$UP_TARBALL" ]; then
	echo "Fetching upstream tarball $UP_DIR/$UP_TARBALL"
	(cd "$UP_DIR" && wget -nv -c -- "$UP_SITE$UP_TARBALL")
else
	echo "Upstream tarball $UP_DIR/$UP_TARBALL exists";
fi

# Extract it
# shellcheck disable=SC2115
rm -rf -- "$UP_DIR/$UP_DISTNAME" "$UP_DIR/$ORIG_DIR" "$UP_DIR/blank"
mkdir -- "$UP_DIR/$UP_DISTNAME"
(cd "$UP_DIR/$UP_DISTNAME" && unzip -x "../$UP_TARBALL")

# Do our magic
# shellcheck disable=SC2248
(cd -- "$UP_DIR/$UP_DISTNAME" && rm -rfv -- $RM_FILES)
cp debian/iepngfix.htc "$UP_DIR/$UP_DISTNAME/ui/default/"
mkdir "$UP_DIR/blank"
(cd "$UP_DIR/blank" && unzip -x -- "$BLANKFILE")
cp -- debian/iepngfix.htc "$UP_DIR/blank/s5-blank/ui/default/"
rm -- "$BLANKFILE"
(cd -- "$UP_DIR/blank" && zip -r -- "$BLANKFILE" *)
mv -- "$UP_DIR/$UP_DISTNAME" "$UP_DIR/$ORIG_DIR"

# Create the repackaged tarball
(cd -- "$UP_DIR" && tar -cf - "$ORIG_DIR" | gzip -cn9 > "$ORIG_NAME.tar.gz")
echo "The repackaged source is at $UP_DIR/$ORIG_NAME.tar.gz"
