#!/bin/sh

set -e
#set -x

. /etc/pkgos/pkgos.conf

ME=$(basename $0)

usage () {
	echo "$ME --old-release OLD_RELEASE --new-release NEW_RELEASE --debian-release DEBIAN_SUITE --jenkins-token JENKINS_TOKEN [--debug]"
	exit 1
}

DEBUG=no
for i in $@ ; do
	case "${1}" in
	"--old-release")
		if [ -z "${2}" ] ; then
			echo "No parameter defining the old release"
			usage
		fi
		OLD_RELEASE=${2}
		shift
		shift
	;;
	"--new-release")
		if [ -z "${2}" ] ; then
			echo "No parameter defining the new release"
			usage
		fi
		NEW_RELEASE=${2}
		shift
		shift
	;;
	"--debian-release")
		if [ -z "${2}" ] ; then
			echo "No parameter defining the Debian release"
			usage
		fi
		DEBIAN_RELEASE=${2}
		shift
		shift
	;;
	"--jenkins-token")
		if [ -z "${2}" ] ; then
			echo "No parameter defining the Jenkins token"
			usage
		fi
		JENKINS_TOKEN=${2}
		shift
		shift
	;;
	"--debug")
		DEBUG=yes
		shift
	;;
	*)
	;;
	esac
done

if [ -z "${OLD_RELEASE}" ] ; then
	echo "No OLD_RELEASE defined."
	usage
fi
if [ -z "${NEW_RELEASE}" ] ; then
	echo "No NEW_RELEASE defined."
	usage
fi
if [ -z "${DEBIAN_RELEASE}" ] ; then
	echo "No DEBIAN_RELEASE defined."
	usage
fi
if [ -z "${JENKINS_TOKEN}" ] ; then
	echo "No JENKINS_TOKEN defined."
	usage
fi
if [ "${DEBUG}" = "yes" ] ; then
	DEBUG_OPT="--debug"
else
	DEBUG_OPT=""
fi

    BLUE="\033[1;34m"
   LGRAY="\033[0;37m"
  NO_COL="\033[0m"
   LBLUE="\033[1;36m"
     RED="\033[1;31m"
   GREEN="\033[1;32m"
   WHITE="\033[1;37m"
  YELLOW="\033[1;33m"
LINEWRAP="\033[7h"
      UP="\033[1A"
    DOWN="\033[1B"
      NL="\033[1E"
      RN="\033[1S"

echo "${GREEN}===> Setting-up default branch to ${NEW_RELEASE}${NO_COL}"
pkgos-salsa-run-on-all-projects pkgos-salsa-set-default-branch --new-release ${NEW_RELEASE} ${DEBUG_OPT}

echo "${GREEN}===> Setting-up build on push for ${NEW_RELEASE}${NO_COL}"
pkgos-salsa-run-on-all-projects pkgos-salsa-set-webhook --new-release ${NEW_RELEASE} --debian-release ${DEBIAN_RELEASE} --jenkins-token ${JENKINS_TOKEN} ${DEBUG_OPT}
