#!/bin/bash
#
# Copyright (c) 2019-2020 Oracle and/or its affiliates. All rights reserved.
# Licensed under the GNU General Public License Version 2 as shown at https://oss.oracle.com/licenses/GPL-2.

whitelist="init
reset
install
status
delete
upgrade
istio-cleanup
"

set -e
kubecfg="$1"
shift
release="$1"
shift
namespace="$1"
shift
act="$1"
shift
cleanup_istio="$1"
shift

echo "kubecfg: $kubecfg release: $release namespace: $namespace act: $act cleanup_istio: $cleanup_istio"
export KUBECONFIG="$kubecfg"

if echo "$whitelist" | grep -q -x "$act"; then
	# In Helm 3, namespaces are not automatically created.  So make the right
	# one if it does not exist yet
	kubectl get namespace "$namespace" || kubectl create namespace "$namespace"

	helm "$act" "$@"

	# Helm sometimes has difficultly cleaning up
	# all resources.  This is especially true when
	# dealing with custom resource types or nonstandard
	# apis.  Nuke everything left over manually, just
	# to be sure.
	if [ "$act" == "delete" ]; then
		delCrd=0

		read -ra resources <<< $(kubectl api-resources -namespaced=true -o name --verbs=list,delete)
		for res in "${resources[@]}"; do
		        # Skip CRDS for now.  If they get deleted too early, there may be
		        # junk left behind.  Instead, delete them at the end of the loop
		        # to ensure any custom resources have gotten deleted first.
		        if [ "$res" == "customresourcedefinitions.apiextensions.k8s.io" ]; then
		                delCrd=1
		                continue
		        fi
		        kubectl -n "$namespace" delete --ignore-not-found -l release="$release" $res
		        echo $?
		done

		# Finally, clean up the CRDs
		if [[ "$delCrd" == "1" ]]; then
		        kubectl -n "$namespace" delete --ignore-not-found -l release="$release" customresourcedefinitions.apiextensions.k8s.io
		fi

		# Istio helm chart doesn't clean up all it's resources so we have to clean them up

    	if [[ "${cleanup_istio}" != "" ]]; then
			set +e
			kubectl delete ClusterRole -l app=istio-init
			kubectl delete ClusterRole -l app=istio
			kubectl delete ClusterRole istio-reader
			kubectl delete ClusterRoleBinding -l app=istio-init
			kubectl delete ClusterRoleBinding -l app=istio
			kubectl delete ClusterRoleBinding istio-init-admin-role-binding-istio-system
			set -e
		fi
	fi
	exit $?
fi

echo "$act cannot be performed by this script"
exit 1
