#!/bin/bash

set -e

APPLICATIONS=""
while (( "$#" )); do
  case "$1" in
    -s|--stand)
      if [ -n "$2" ]; then
        STAND_TICKET=$2
        shift 2
      else
        echo "Error: Name of stand is missing" >&2
        exit 1
      fi
      ;;
    -*|--*=) # unsupported flags
      echo "Error: Unsupported flag $1" >&2
      exit 1
      ;;
    *) # preserve positional arguments
      APPLICATIONS="${APPLICATIONS} $1"
      shift
      ;;
  esac
done

if [ -z "${STAND_TICKET}" ]; then
  STAND_TICKET=$(releaser stand-ticket \
                        --no-get-ticket-from-last-commit-message \
                        --get-ticket-from-current-branch-name \
                   | tr '[:upper:]' '[:lower:]')
fi

if [ -z "${APPLICATIONS}" ]; then
  APPLICATIONS="forms_int forms_ext forms_ext_admin forms_biz"
fi

for application in $(echo "${APPLICATIONS}" | tr ' ' '\n'); do
  case "${application}" in
    forms_int)
        releaser env-delete \
                 --project tools \
                 --application forms-back-int \
                 --environment "stand-${STAND_TICKET}"
    ;;
    forms_ext)
        releaser env-delete \
                 --project tools \
                 --application forms-back-ext \
                 --environment "stand-${STAND_TICKET}"
    ;;
    forms_ext_admin)
        releaser env-delete \
                 --project tools \
                 --application forms-back-ext-admin \
                 --environment "stand-${STAND_TICKET}"
    ;;
    forms_biz)
        releaser env-delete \
                 --project tools-b2b \
                 --application forms-back-biz \
                 --environment "stand-${STAND_TICKET}"
    ;;
  esac
done

scripts/front_stand.py drop "${STAND_TICKET}" ${APPLICATIONS}
