#!/bin/sh

set -e

DEB_VERSION_UPSTREAM=$(dpkg-parsechangelog -SVersion | sed -e 's/-[^-]*$//' -e 's/^[0-9]*://')
UPSTREAM_VERSION=${GBP_UPSTREAM_VERSION:-$DEB_VERSION_UPSTREAM}

ORIG_TARBALL=$(realpath "../puppet-agent_${UPSTREAM_VERSION}.orig-modules.tar.gz")
MODULES_TEMP=$(mktemp -d modules.XXXXXX)
WORKING_DIR="${PWD}"

cleanup() {
    cd "${WORKING_DIR}"
    rm -rf "${MODULES_TEMP}"
}

trap "cleanup" EXIT TERM INT

if [ -e "$ORIG_TARBALL" ]; then
    echo "existing modules-orig tarball found at ${ORIG_TARBALL}, aborting!"
    exit 1
fi

echo "downloading core modules for puppet-agent ${UPSTREAM_VERSION} ..."

cd "$MODULES_TEMP" >/dev/null
mkdir modules

# extract list of core modules for upstream build script
wget -q "https://github.com/puppetlabs/puppet-agent/raw/${UPSTREAM_VERSION}/configs/projects/puppet-agent.rb"

grep -Po 'proj.component "\Kmodule-\S+(?=")' puppet-agent.rb |  while read -r module; do

    echo "getting info for ${module}"
    # module names are formatted explicitly
    # see https://github.com/puppetlabs/puppet-agent/blob/8.4.0/configs/components/_base-module.rb#L13-L14
    module_author=$(echo "$module" | grep -Po "module-\K\S+(?=-\S+)")
    module_name=$(echo "$module" | grep -Po "module-${module_author}-\K\S+")

    # process module properties
    module_properties=$(wget -q "https://github.com/puppetlabs/puppet-agent/raw/${UPSTREAM_VERSION}/configs/components/${module}.json" -O - | jq -r '"\(.url)\t\(.ref)"')
    module_github_path=$(echo "$module_properties" | cut -f1 | grep -Po "git@github.com:\K\S+(?=\.git)")
    module_version=$(echo "$module_properties" | cut -f2 | grep -Po "tags/v\K[\d\.]+")

    # download module from github tagged release
    echo "downloading ${module_name} version '${module_version}'"
    wget -q "https://github.com/${module_github_path}/archive/refs/tags/v${module_version}.tar.gz" -O - | tar -x -z

    # move module into place
    mv "${module_author}-${module_name}-${module_version}" modules
done

cd modules >/dev/null

tar -c -a --exclude=.* -f "$ORIG_TARBALL" -- *
echo "created component tarball at: ${ORIG_TARBALL}"

cd "$WORKING_DIR"
pristine-tar commit "$ORIG_TARBALL"

echo "all done!"
