#!/bin/bash
#
# get original data
#
test "x$1" = "x" && echo "Error: tarball version required" && exit 1;
VERSION="$1"
TARBALL="claws-mail-themes-${VERSION}.tar.gz"
test ! -f "$TARBALL" && echo "Error: tarball $TARBALL not found" && exit 2;
echo -n "Extracting... "
tar xzf "$TARBALL" && echo OK 
TARDIR=${TARBALL/.tar.gz/}
test ! -d "$TARDIR" && echo "Error: $TARDIR not created from tarball" && exit 3;
#
# prepare for patch
#
AC="$TARDIR/configure.ac"
AM="$TARDIR/Makefile.am"
test ! -f "$AC" && echo "Error: $AC not found" && exit 4;
test ! -f "$AM" && echo "Error: $AM not found" && exit 5;
echo -n "Preparing... "
TARDIRORIG="${TARDIR}.orig"
rm -rf "$TARDIRORIG" \
  && mkdir "$TARDIRORIG" \
  && cp -fp "$AC" "$AM" "$TARDIRORIG/" \
  && echo OK
#
# removal of non DFSG themes:
# buuf -> No license and original artwork seems under CC BY-SA-NC 2.5 license,
#         see http://mattahan.deviantart.com/art/Buuf-37966044
# hash303030 -> Under CC BY-NC-SA 3.0
# hashA0A0A0 -> Derived from hash303030, same license
# TangoClaws-0.3 -> Under CC BY-SA 2.5 license
# TangoOrbit -> Under CC BY-SA 2.5 license
# GurUnix -> Only free for personal use, selling and redistribution of 
#            modifications forbidden
# ZX-0_1.1 -> No license file, previous version was under CC BY-SA 2.5
#
echo -n "Removing... "
for THEME in "buuf" "hash303030" "hashA0A0A0" "TangoClaws-0.3" "TangoOrbit" "GurUnix" "ZX-0_1.1";
do rm -rf "$TARDIR/$THEME"
   grep -v "$THEME" "$AC" > "${AC}_"
   diff "$AC" "${AC}_" > /dev/null \
     && echo "Error: removing $THEME from $AC failed" && exit 6;
   touch -r "$AC" "${AC}_" && rm -f "$AC" && mv "${AC}_" "$AC"
   cat "$AM" | sed "s, $THEME,," > "${AM}_"
   diff "$AM" "${AM}_" > /dev/null \
     && echo "Error: removing $THEME from $AM failed" && exit 7;
   touch -r "$AM" "${AM}_" && rm -f "$AM" && mv "${AM}_" "$AM"
   echo -n "$THEME "
done
echo ""
#
# create patch for build system files
#
echo -n "Creating patch... "
PATCH="remove-non-free-themes"
echo "Subject: Remove non-DFSG themes from build" > "$PATCH"
echo "Author: Ricardo Mones <mones@debian.org>" >> "$PATCH"
diff -uN "$TARDIRORIG/Makefile.am" "$AM" >> "$PATCH"
diff -uN "$TARDIRORIG/configure.ac" "$AC" >> "$PATCH"
test -s "$PATCH" \
  && cp -pf "$TARDIRORIG/Makefile.am" "$AM" \
  && cp -pf "$TARDIRORIG/configure.ac" "$AC" \
  && rm -rf "$TARDIRORIG" && echo OK
#
# recreate tarball
#
echo -n "Repackaging... "
rm -f "$TARBALL.upstream" \
  && mv "$TARBALL" "$TARBALL.upstream" \
  && mv "$TARDIR" "${TARDIR}.dfsg" \
  && env GZIP="-9" tar czf "$TARBALL" "${TARDIR}.dfsg" \
  && echo OK

