#!/bin/sh

# 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 -eux

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

CHANGES="$(find . -name '*.changes')"

# upload only version-specific .deb files when requested
if [ "${upload:-all}" = "extension-only" ]; then
	for c in $CHANGES; do
		# remove all .debs that do not match -1x or -9.x
		NONEXTDEBS=$(dcmd --deb echo $c | xargs -n1 | grep -Ev -- '[^_]-(1[0-9]|9\.[0-6])[-_]' | sed -e 's!.*/!!')
		[ -z "$NONEXTDEBS" ] && continue # only version-specific .debs in there
		changestool $c dumbremove $NONEXTDEBS
	done
fi

dcmd chmod a+r $CHANGES

# 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
