#!/bin/sh

set -eu

case $JOB_NAME in
  *-binaries-snapshot*) SOURCE_REPO_DIST="$distribution-pgdg-source-snapshot" ;;
  *-binaries*) SOURCE_REPO_DIST="$distribution-pgdg-source" ;;
  *) echo "JOB_NAME $JOB_NAME does not match *-binaries*"
    exit 1
    ;;
esac
PACKAGE=${JOB_NAME%%-binaries*}

URL="https://jengus.postgresql.org/userContent/apt"
SOURCESFILE="$URL/dists/$SOURCE_REPO_DIST/main/source/Sources.xz"

echo "Retrieving $SOURCESFILE"
curl --no-progress-meter -fO --netrc "$SOURCESFILE"
rm -f Sources
unxz Sources.xz
if ! SOURCE=$(grep-dctrl --exact-match -P $PACKAGE Sources); then
    echo "Error: could not find $PACKAGE in Sources.file"
    echo
    exit 1
fi
echo
echo "$SOURCE"
echo
VERSION=$(echo "$SOURCE" | grep-dctrl -s Version -n .)
DIR=$(echo "$SOURCE" | grep-dctrl -s Directory -n .)
FILES=$(echo "$SOURCE" | grep-dctrl -s Files -n .)
echo "$VERSION" > version.txt

echo "$FILES" | while read md5 size name; do
    if [ "$name" ]; then
        echo "Downloading $URL/$DIR/$name"
        curl -f --netrc -O "$URL/$DIR/$name"
    fi
done
echo

ls -l $PACKAGE*
echo

dscverify --nosigcheck $PACKAGE*.dsc
echo

rm -f Sources Sources.xz
