#!/bin/sh

# ./trigger-job -g debian apgdiff
# ./trigger-job -b 'Rebuild against python 3.8' -d bullseye postgresql-12-binaries
# ./trigger-job dput 'binaries=postgresql-12-binaries'

# ~/.netrc:
#machine pgdgbuild.dus.dg-i.net login <username> password <your-api-token>

set -e

while getopts "Aa:b:B:d:g:nq:r:u" opt ; do
  case $opt in
    A) autopkgtest="autopkgtest=skip" ;;
    a) architecture="architecture==\"$OPTARG\"" ;;
    b) binnmu_reason="binnmu_reason=$OPTARG"
      : ${binnmu_version:=binnmu_version=1} ;;
    B) binnmu_version="binnmu_version=$OPTARG" ;;
    d) distribution="distribution==\"$OPTARG\"" ;;
    g) branch="branch=$OPTARG" ;;
    n) DEB_BUILD_OPTIONS="DEB_BUILD_OPTIONS=nocheck" ;;
    q) queue="queue=$OPTARG" ;;
    r) revision="revision=$OPTARG" ;;
    u) upload="upload=extension-only" ;;
    *) exit 5 ;;
  esac
done
# shift away args
shift $(($OPTIND - 1))

JOB="$1"
shift

if [ "$architecture" ] && [ "$distribution" ]; then
  matrix="matrix=$architecture%26%26$distribution"
elif [ "$architecture" ]; then
  matrix="matrix=$architecture"
elif [ "$distribution" ]; then
  matrix="matrix=$distribution"
fi

IFS="&"
set -- $branch $revision $binnmu_reason $binnmu_version $autopkgtest $DEB_BUILD_OPTIONS $queue $upload $matrix "$@" token=buildnow

set -x
curl -f --netrc \
  "https://pgdgbuild.dus.dg-i.net/job/$JOB/buildWithParameters" \
  --data "$*"

#for JOB in $JOB{,-source,-binaries,-autopkgtest,-autopkgtest-beta,-source-snapshot,-binaries-snapshot}; do
#curl --netrc -X POST "https://pgdgbuild.dus.dg-i.net/job/$JOB/doDelete"
#done
