#!/bin/sh
#
# repack a zip file, as reproducibly as possible
# downloads the zip, extract it, create tarball
# with members in the same order as original zip file
# but with ownership root:root and perms a+X

cleanup() {
   [ -d "$TEMP_D" ] || rm -Rf "$TEMP_D"
}
fail() { echo "$@" 1>&2; exit 1; }

TEMP_D=$(mktemp -d)
trap cleanup EXIT

start_d=$PWD

[ $# -eq 1 ] || { echo "must give input zip file"; exit 1; }
input=${1}

zip=${input##*/}
case "$input" in
   http://*|https://*|ftp://*)
      echo "downloading ${input}"
      wget -q "$input" -O "$TEMP_D/${zip}"
      ;;
   *) cp "$input" "${TEMP_D}/${zip}";;
esac
[ $? -eq 0 ] || fail "failed to get ${input} to tempdir"

cd "$TEMP_D"
unzip -a "$zip" > .zip.contents || fail "failed to unzip ${zip}"

for f in *; do
   [ "$f" = "$zip" ] && continue
   [ -z "$tld" ] || fail "multiple top level content in ${zip} [$f]"
   tld=$f
done

ver=${tld#*-}
awk '($1 == "creating:" || $1 == "inflating:") { print $2 }' \
   .zip.contents > contents

GZIP='-n -9' tar --owner=root --group=root --mode=a+rX \
   --no-recursion --files-from contents \
   -czf "${start_d}/${tld}.tar.gz" ||
   fail "failed to create ${tld}.tar.gz"

echo "created ${tld}.tar.gz from ${input}" 1>&2
