#!/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.

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

set -eo pipefail

K8S_setKubeConfig "$PLUGININSTANCE" "$dir/kubeconfig"

getValueList seeds "seeds" PLUGINCONFIGJSON
getValueList namespace "namespace" PLUGINCONFIGJSON

deploy() {
    verbose "Nothing to do on deploy."
}

# fail if shoots are found
# if a namespace is given, only look in that namespace for shoots
# if one or more seeds are given, filter for shoots that use one of these seeds
delete() {
    shoots=
    seed=
    if [ ${#seeds[@]} -eq 0 ]; then
        # if no seeds are specified
        shoots=$(get_shoots ${namespace:-""})
    else
        # if seeds are specified
        for s in ${seeds[@]}; do
            shoots=$(get_shoots ${namespace:-""} "$s")
            if [ -n "$shoots" ]; then
                seed=$s
                break
            fi
        done
    fi
    if [ -n "$shoots" ]; then
        # a shoot has been found
        if [ -n ${namespace:-""} ]; then
            nsmsg=" in namespace '$namespace'"
        else
            nsmsg=
        fi
        if [ -n "$seed" ]; then
            semsg=" on seed '$seed'"
        else
            semsg=
        fi
        fail "There seem to be shoots left$nsmsg$semsg!"
    else
        info "No conflicting shoots found."
    fi
}

get_shoots() {
    namespace=${1:-""}
    seed=${2:-""}

    if [ -n "$namespace" ]; then
        nsmod="-n $namespace"
    else
        nsmod="--all-namespaces"
    fi
    if [ -n "$seed" ]; then
        smod="--field-selector spec.cloud.seed=$seed"
    else
        smod="--no-headers"
    fi
    if ! shoots=$(kubectl get shoots $nsmod $smod 2> "$dir/error_log.txt"); then
        err=$(cat "$dir/error_log.txt")
        if [ "$err" != "error: the server doesn't have a resource type \"shoots\"" ]; then
            fail "$err"
        fi
    fi
    echo "$shoots"
}

case "$1" in
    deploy) deploy "$@";;
    delete) delete "$@";;
    *) fail "unsupported action $1"
esac