#!/bin/sh

set -e

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

ORIG_TARBALL=$(realpath "../openvox_${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 openvox-agent ${UPSTREAM_VERSION} ..."

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

# iterate through list of core modules
grep -Po 'proj.component "\Kmodule-\S+(?=")' ../packaging/configs/projects/openvox-agent.rb | while read -r module; do

    echo "getting info for ${module}"
    # module names are formatted explicitly
    # (see packaging/configs/components/_base-module.rb)
    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=$(jq -r '"\(.url)\t\(.ref)"' "../packaging/configs/components/${module}.json")
    module_github_path=$(echo "$module_properties" | cut -f1 | grep -Po "https://github.com/\K\S+(?=\.git)")
    module_version=$(echo "$module_properties" | cut -f2 | grep -Po "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!"
