#!/usr/bin/env bash
#
# Copyright 2019 Copyright (c) 2019 SAP SE or an SAP affiliate company. All rights reserved. This file is licensed under the Apache Software License, v. 2 except as noted otherwise in the LICENSE file.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# Helper plugin to delete resources

source "$SOWLIB/pluginutils"
source "$SOWLIB/k8s"

set -eo pipefail

# handle necessary delete preparation
# args: type name [namespace]
prepare_delete() {
    case "$1" in
        seed)
            # abort if any shoot is still using the given seed
            verbose "Check if shoots are still running on seed '$1' ..."
            if [[ $(kubectl get shoots --all-namespaces -o json | jq -r 'reduce (.items[].spec.seedName | . == "'$2'") as $b (false; . or $b)') == "true" ]]; then
                fail "there are still shoots running on seed '$2'"
            fi
            ;;
        shoot)
            ;&
        project)
            # annotate shoot/project
            exec_cmd kubectl ${3:+"-n"}${3:-} annotate "$1" "$2" confirmation.gardener.cloud/deletion=true --overwrite
            ;;
    esac
}

K8S_setKubeConfig "$PLUGININSTANCE" "$dir/kubeconfig"
getRequiredValue type "type" PLUGINCONFIGJSON
getRequiredValue name "name" PLUGINCONFIGJSON
getRequiredValue step "step" PLUGINCONFIGJSON
getValue namespace "namespace" PLUGINCONFIGJSON

case "$1" in
    deploy) ;&
    delete)
        if [[ "$step" == "$1" ]]; then
            prepare_delete $type $name $namespace
            exec_cmd kubectl delete ${namespace:+"-n"}${namespace:-} $type $name --ignore-not-found
        else
            verbose "Nothing to do on $1."
        fi
        ;;
    *) fail "unsupported action $1"
esac