#!/bin/sh -e

# Upstream provides unversioned download thus we need to read the version out of the source code

COMPRESS=xz

NAME=`dpkg-parsechangelog | awk '/^Source/ { print $2 }'`
OVERSION=`dpkg-parsechangelog | awk '/^Version:/ { print $2 }' | sed 's/\([0-9\.]\+\)-[0-9]\+$/\1/'`

mkdir -p ../tarballs
cd ../tarballs

wget --quiet -N https://www.cog-genomics.org/static/bin/plink/plink_src.zip
rm -rf 1.9
unzip -q plink_src.zip
cd 1.9
# grep -A20 'char ver_str\[\]' plink.c | grep -e 'PLINK v1.90b6' -e ' 202[0-9])' | sed '1{N;s/\n//;}'
plver=$(grep -A10 'char ver_str\[\]' plink.c | grep -e 'PLINK v1.90b[0-9.]\+' | sed 's/^[[:space:]]*"PLINK v\([0-9.b]\+\)".*/\1/' | sed 's/b/~b/')
datever=$(grep -A20 'char ver_str\[\]' plink.c | grep -e ' 202[0-9])' | sed 's/^[[:space:]]*" (\([0-9]\+ .* 20[0-9]\+\))";/\1/')
datever=$(date "+%y%m%d" --date="${datever}")
VERSION="$plver-$datever"
if dpkg --compare-versions $VERSION gt $OVERSION ; then
  echo "$VERSION is greater than $OVERSION ... create new tarball"
else
  exit
fi
cd ..
TARDIR=${NAME}-${VERSION}
mv 1.9 ${TARDIR}

GZIP="--best --no-name" tar --owner=root --group=root --mode=a+rX -caf "$NAME"_"$VERSION".orig.tar.${COMPRESS} "${TARDIR}"
rm -rf ${TARDIR}
