#!/bin/bash
# @description Upgrade directives to use latest technique version available
# @man This command will migrate directives based on a given technique to the given version.
# @man If the directive version cannot be changed for any reason, the directive is skipped.
# @man +
# @man *Options*:
# @man +
# @man *-v*: run in verbose mode, prints detailed information
# @man +
# @man *-n*: upgrade directves based on given technique (mandatory)
# @man +
# @man *-c*: run without colors
# @man +
# @man *-V*: migrate to given version

. "${BASEDIR}/../lib/common.sh"
. "${BASEDIR}/../lib/api_call.sh"

DISPLAY_COMMAND=false

while getopts "vcn:V:" opt; do
  case $opt in
    v)
      DISPLAY_COMMAND=true
      ;;
    n)
      TECHNIQUE_NAME="${OPTARG}"
      ;;
    c)
      clear_colors
      ;;
    V)
      TECHNIQUE_VERSION="${OPTARG}"
  esac
done

if [ -z "${TECHNIQUE_VERSION}" ]
then
  TECHNIQUE_VERSION="latest"
fi

if [ "${TECHNIQUE_VERSION}" == "latest" ]
then
# Find the newest technique version
  TECHNIQUE_VERSION=$(rudder_api_call "/techniques" "GET" "" "${DISPLAY_COMMAND}" | jq -r ".data | .techniques[] | select( .name == \"${TECHNIQUE_NAME}\") | .versions[]" | tail -n1 )
  if [ -z "${TECHNIQUE_VERSION}" ];
  then
    printf "${RED}No version found for the technique ${TECHNIQUE_NAME}${NORMAL}\n"
    exit 1
  fi
fi

echo "TECHNIQUE ${TECHNIQUE_NAME} will migrate to ${TECHNIQUE_VERSION}"
echo ""

# Find the directives using the given technique
DIRECTIVES=$(rudder_api_call "/directives" "GET" "" "${DISPLAY_COMMAND}" | jq -r ".data.directives[] | select(.techniqueName==\"${TECHNIQUE_NAME}\") | .id" | sed 's/\"//g' )

echo "Directives using the '${TECHNIQUE_NAME}' technique:"
printf "${BLUE}${DIRECTIVES}${NORMAL}\n\n"

if [ -z "${DIRECTIVES}" ];
then
  printf "  ${RED}No directive found using the technique ${NORMAL}${TECHNIQUE_NAME}\n"
else
  while IFS= read
  do
    # Change the version parameter in the previously found directives (ie 1 directive = 1 technique)
      echo "Treating $REPLY"
      result=$(rudder_api_call "/directives/$REPLY" "POST" "-d \"techniqueVersion=${TECHNIQUE_VERSION}\"" "${DISPLAY_COMMAND}")
      code1=$?
      post_result=$(rudder_api_call "/directives/$REPLY" "GET" "" "${DISPLAY_COMMAND}" | jq -r ".data.directives[].techniqueVersion")

      if [ ${code1} -eq 0 ] && [ "${post_result}" = "${TECHNIQUE_VERSION}" ]
      then
        printf "  ${GREEN}ok${NORMAL}: Changed technique version to ${GREEN}${post_result}${NORMAL} for directive: '$REPLY'.\n\n"
      else
        printf "  ${RED}error${NORMAL}: Could not change technique version for directive: '$REPLY'.\n"
        echo "  ${result}"
        exit 1
      fi
  done <<< "${DIRECTIVES}"
fi

