#!/bin/bash

set -o errexit
set -o nounset
set -o pipefail
REPO_ROOT=$(dirname ${BASH_SOURCE})/..
KUSTOMIZE="${1}"
if [ -z "${KUSTOMIZE}" ]; then
    echo "Usage: $0 <path-to-kustomize-binary>"
    exit 1
fi

cd "${REPO_ROOT}"

# generate_all_in_one_manifest expects the following parameters:
# Params:
#   - $1 - Path to the configuration file
#   - $2 - Path to resulting file
function generate_all_in_one_manifest()
{
    echo "Generating kustomize manifest for ${1} in ${2}"
    echo -e '# Generated by build-single-manifest.sh. NOT FOR PRODUCTION USE (only used internally for testing). DO NOT EDIT.\n' > "${2}"
    "${KUSTOMIZE}" build "${1}" >> "${2}"
}

function generate_deprecation_message()
{
    echo "Generating manifest with deprecation info in ${1}"
cat << EOF > "${1}"
# Generated by build-single-manifest.sh. DO NOT EDIT.
#
# DEPRECATED
#
# For Kong Ingress Controller 3.0+, please use Helm instead:
#
#   $ helm repo add kong https://charts.konghq.com
#   $ helm repo update
#   $ helm install kong/kong --generate-name --set ingressController.installCRDs=false
#
# If you intend to use an older version, Helm is recommended but you still have the option
# to install using manifests. In that case, replace the 'main' branch in your link with the
# KIC tag. For example:
# kubectl apply -f https://raw.githubusercontent.com/Kong/kubernetes-ingress-controller/v2.12.0/${1}
#

apiVersion: please-use-helm-to-install-kong
kind: Deprecated
EOF
}


MANIFESTS=(
    'postgres all-in-one-postgres.yaml'
    'enterprise all-in-one-dbless-k4k8s-enterprise.yaml'
    'enterprise-postgres all-in-one-postgres-enterprise.yaml'
    'multi-gw/oss all-in-one-dbless.yaml'
    'multi-gw-postgres/oss all-in-one-postgres-multiple-gateways.yaml'
    'konnect/oss all-in-one-dbless-konnect.yaml'
    'konnect/enterprise all-in-one-dbless-konnect-enterprise.yaml'
)

for MANIFEST in "${MANIFESTS[@]}"; do
    set -- ${MANIFEST} # Unpack tuple-like structure MANIFESTS.
    generate_all_in_one_manifest "config/variants/${1}" "test/e2e/manifests/${2}"
    generate_deprecation_message "deploy/single/${2}"
done
