#!/bin/sh
# This gets/makes an original tarball.
# By default, it uses the version in debian/changelog.
# (By default using a tagged release)
# This means that if you are upgrading upstream versions, please override VER in the environment!
set -e

COMMIT_HASH=
# Only set explicitly in case we need a snapshot between releases
# COMMIT_HASH=3d405f6a0427c411d30cc7ef4129e2e887f35e28
REPACK_SUFFIX=$(dpkg-parsechangelog -S Version | sed -E 's/.*([+~]dfsg[0-9]*)-.*/\1/')

if [ "${VER}" = "" ]; then
    VER=$(dpkg-parsechangelog -S Version | sed -e 's,.*:,,' -e 's,[+~]dfsg.*,,')
    echo "# Parsed upstream version to acquire from debian/changelog: $VER"
else
    echo "# Version to acquire overridden by environment: VER=$VER"
fi
echo "# REPACK_SUFFIX ${REPACK_SUFFIX}"

for cmd in jq curl wget; do
    if ! command -v $cmd > /dev/null; then
        echo "# Need to install $cmd!"
        exit 1
    fi
done

if [ "${COMMIT_HASH}" = "" ]; then
    echo "# Looking up SHA for MeshLab version ${VER}"
    COMMIT_HASH=$(curl -s https://api.github.com/repos/cnr-isti-vclab/meshlab/git/ref/tags/MeshLab-${VER} | jq --raw-output '.object.sha' | tr "[:upper:]" "[:lower:]")
fi

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..."
SRC_TREE=$(curl -s https://api.github.com/repos/cnr-isti-vclab/meshlab/git/trees/${COMMIT_HASH} | jq --raw-output '(.tree[] | select(.path == "src") ).sha' | tr "[:upper:]" "[:lower:]")
echo "## Looking in tree ${SRC_TREE}"
VCGLIB_HASH=$(curl -s https://api.github.com/repos/cnr-isti-vclab/meshlab/git/trees/${SRC_TREE} | 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 -p "meshlab-${COMMIT_HASH}/src/"
    mv vcglib "meshlab-${COMMIT_HASH}/src/"
    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"


echo "# Run the following to update debian/copyright:"
echo "sed -i 's:meshlab/archive/.*:meshlab/archive/${COMMIT_HASH}.tar.gz:' debian/copyright"
echo "sed -i 's:vcglib/archive/.*:vcglib/archive/${VCGLIB_HASH}.tar.gz:' debian/copyright"
