#/bin/bash

# Usage:  ./delete_be_api.sh backendapiname

#require curl, jq, tr
set -e
server=adminnodemanager_hostname
port=8090
instance=instance-1
username=admin
password=changeme
apiname=$1

#retrieve api id
# /!\ could be the wrong one if several api has the same name 
apiid=$(curl --silent -k -u "${username}:${password}" "https://${server}:${port}/api/router/service/${instance}/api/kps/PortalAPI?filter=${apiname}" | jq -r ".[].id" | tr -d '[:space:]')

#loop to retrieve method and clean them in apiportalvirtualizedapimethod
#if no method is returned, jq return an error and the script exit
methodid=$(curl --silent -k -u "${username}:${password}" "https://${server}:${port}/api/router/service/${instance}/api/kps/ext/query/PortalVirtualizedAPIMethod?apiId=${apiid}" | jq -r ".[].id"  | tr -d '[:space:]')
while [ "a${methodid}" != "a" ]
do
    echo "Clean ${methodid}"
    curl -k -u "${username}:${password}" -X DELETE "https://${server}:${port}/api/router/service/${instance}/api/kps/PortalVirtualizedAPIMethod/${methodid}"
    methodid=$(curl --silent -k -u "${username}:${password}" "https://${server}:${port}/api/router/service/${instance}/api/kps/ext/query/PortalVirtualizedAPIMethod?apiId=${apiid}" | jq -r ".[].id"  | tr -d '[:space:]')
done