#!/bin/sh

# input:
#   .changes files copied from upstream job
#   $binaries (upstream job name including -binaries suffix)
#   $queue (optional, default "incoming")
#   $JENKINS_URL (from Jenkins)

# read pgapt config
for dir in . .. $HOME/apt.postgresql.org; do
  test -f $dir/pgapt.conf || continue
  . $dir/pgapt.conf
  PGAPTDIR="$dir"
  break
done

QUEUE="${1:-incoming}"

ls -AlR

[ "$QUEUE" = "discard" ] && exit 0

set -eu

if [ "${upload:=all}" = "extension-only" ]; then
  find . -name '*_source.changes' -delete
fi

CHANGES="$(find . -name '*.changes')"
dcmd chmod a+r $CHANGES

# get build logs from Jenkins
for c in $CHANGES; do
  dir=$(dirname $c)
  base=$(basename $c .changes)
  OLDIFS="$IFS"
  IFS="_"
  set -- $base
  IFS="$OLDIFS"
  package="$1"
  version="$2"
  architecture="$3"

  # extract changelog from source package and add it to the _source.changes file
  if [ "$architecture" = "source" ]; then
    dsc=$(dcmd --dsc $c)
    changelog=$dir/${package}_${version}.changelog
    (
      set -x
      dscextract $dsc debian/changelog > $changelog
      grep -q "^$package (" $changelog
      changestool $c add $changelog
    )
    continue
  fi

  # upload only version-specific .deb files when requested
  if [ "$upload" = "extension-only" ]; then
    # remove all .debs that do not match -1x
    NONEXTDEBS=$(dcmd --deb $c | grep -v '[^_]-[12][0-9][-_]' | sed -e 's!.*/!!')
    if [ "$NONEXTDEBS" ]; then
      (
        set -x
        changestool $c dumbremove $NONEXTDEBS
      )
    fi
  fi
done

set -x

# upload packages
dcmd rsync -av $CHANGES $REPO_HOST:$REPO_FILE_PATH/$QUEUE

case $QUEUE in
  incoming|snapshot) ;;
  *) exit 0 ;;
esac

# call processincoming once for all packages uploaded
ssh $REPO_HOST sudo -u aptuser $REPO_FILE_PATH/repo/processincoming $QUEUE
