#!/bin/sh

set -e

. /etc/pkgos/pkgos.conf

ME=$(basename $0)

usage () {
	echo "$ME <--project-name PROJECT_NAME / --project-id PROJECT_ID>"
	exit 1
}


if [ -z "${SALSA_TOKEN}" ] ; then
	echo "The \$SALSA_TOKEN variable is empty. Please export it with" >/dev/stderr
	echo "a valid salsa.debian.org token as content." >/dev/stderr
	exit 1
fi

for i in $@ ; do
	case "${1}" in
	"--project-id")
		if [ -z "${2}" ] ; then
			echo "No parameter defining the project ID."
			usage
		fi
		PROJECT_ID=${2}
		shift
		shift
	;;
	"--project-name")
		if [ -z "${2}" ] ; then
			echo "No parameter defining the project name."
			usage
		fi
		PROJECT_NAME=${2}
		shift
		shift
	;;
	"--debug")
		DEBUG=yes
		shift
	;;
	*)
	;;
	esac
done

if [ -z "${PROJECT_ID}" ] ; then
	if [ -z "${PROJECT_NAME}" ] ; then
		usage
	fi

	PROJECT_ID=$(pkgos-salsa-get-project-id --project-name ${PROJECT_NAME})
	if [ -z "${PROJECT_ID}" ] ; then
		echo "Cannot find project id for ${PROJECT_NAME}"
		exit 1
	fi
fi

RECIPIENTS=dispatch@tracker.debian.org

curl -s --header "PRIVATE-TOKEN: $SALSA_TOKEN" -XPUT https://salsa.debian.org/api/v4/projects/${PROJECT_ID}/integrations/emails-on-push \
	--data "recipients=$RECIPIENTS"
