#!/bin/sh
set -e

COMMIT_HASH=f3568e75c9aed6da8bb105a1c8ac7ebbe00e4536
REPACK_SUFFIX=$(dpkg-parsechangelog -S Version | sed -E 's/.*([+~]dfsg[0-9]+)-.*/\1/')
VER=$(dpkg-parsechangelog -S Version | sed -e 's,.*:,,' -e 's,+dfsg.*,,')

echo "# MeshLab downloading commit ${COMMIT_HASH} ..."
wget --continue -O meshlab_${VER}.orig.tar.gz https://github.com/cnr-isti-vclab/meshlab/archive/${COMMIT_HASH}.tar.gz


echo "# Determining vcglib commit..."
VCGLIB_HASH=$(curl -s https://api.github.com/repos/cnr-isti-vclab/meshlab/git/trees/${COMMIT_HASH} | jq --raw-output '(.tree[] | select(.path == "vcglib") ).sha' | tr [:upper:] [:lower:])


echo "# vcglib commit ${VCGLIB_HASH} downloading..."
wget --continue -O meshlab_vcglib_${VER}.orig.tar.gz https://github.com/cnr-isti-vclab/vcglib/archive/${VCGLIB_HASH}.tar.gz

echo "# Decompressing MeshLab"
gunzip "meshlab_${VER}.orig.tar.gz"

BASE_DIR=$(pwd)
export BASE_DIR
REPACK_DIR=$(mktemp -d)
trap "rm -rf $REPACK_DIR" EXIT
(
    echo "# Extracting vcglib"
    cd "$REPACK_DIR"
    tar xzf "${BASE_DIR}/meshlab_vcglib_${VER}.orig.tar.gz" --transform="s/-${VCGLIB_HASH}//"
    mkdir meshlab-${COMMIT_HASH}
    mv vcglib meshlab-${COMMIT_HASH}/
    echo "# Appending vcglib to tarball"
    tar rf "${BASE_DIR}/meshlab_${VER}.orig.tar" meshlab-${COMMIT_HASH}
)


echo "# Repacking with mk-origtargz"
mk-origtargz --repack --compression xz -S ${REPACK_SUFFIX} -C .. "meshlab_${VER}.orig.tar" -v ${VER}

echo "# Cleaning up files"
rm -f "meshlab_vcglib_${VER}.orig.tar.gz" "meshlab_${VER}.orig.tar"
