#!/bin/bash

# Copyright 2018 The Kubernetes Authors.
#
# 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.

set -o errexit
set -o nounset
set -o pipefail

VERSION="1.3.0"

SCRIPT_ROOT=$(dirname ${BASH_SOURCE})/${VERSION}

ACTION=$1
COMPONENTS="vpa-v1-crd-gen vpa-rbac updater-deployment recommender-deployment admission-controller-deployment"

function script_path {
  if test -f "${SCRIPT_ROOT}/${1}.yaml"; then
    echo "${SCRIPT_ROOT}/${1}.yaml"
  else
    echo "${1}.yaml not found in ${SCRIPT_ROOT}"
  fi
}

if [ $# -gt 1 ]; then
  COMPONENTS="$2-deployment"
fi

for i in $COMPONENTS; do
  if [ $i == admission-controller-deployment ] ; then
    if [[ ${ACTION} == create || ${ACTION} == apply ]] ; then
      # Allow gencerts to fail silently if certs already exist
      (bash ${SCRIPT_ROOT}/../hack/gencerts.sh || true)
    elif [ ${ACTION} == delete ] ; then
      (bash ${SCRIPT_ROOT}/../hack/rmcerts.sh || true)
      (bash ${SCRIPT_ROOT}/../hack/delete-webhook.sh || true)
    fi
  fi
  ${SCRIPT_ROOT}/../hack/process-yaml.sh $(script_path $i) | kubectl ${ACTION} -f - || true
done