#!/bin/bash

set -o xtrace
set -o errexit
#set -o pipefail

#replica of tree comand using find and sed
function tree() {
  find ${1:-.} | sed -e "s/[^-][^\/]*\//  |/g" -e "s/|\([^ ]\)/|-\1/"
}

# Set magic variables for current file & dir
__dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

EXPECTED_ENV_VARS=(CHANNEL OPERATOR_CONTAINER_IMAGE METADATA_DESCRIPTION NAME DISPLAY_NAME
    BACKEND_IMAGE APICAST_IMAGE SYSTEM_IMAGE ZYNC_IMAGE MEMCACHED_IMAGE OC_CLI_IMAGE
    REDIS_5_IMAGE MYSQL_8_IMAGE POSTGRESQL_10_IMAGE
    DOC_URL MATURITY PROVIDER_NAME CSV_VERSION VALID_SUBSCRIPTION)

source $__dir/3scale.properties

for var in "${EXPECTED_ENV_VARS[@]}"
do
    if [[ -z "${!var}" ]]
    then
      echo "$var not defined or empty"
      exit 1
    fi
    # extend scope to subshells
    # shellcheck disable=SC2163
    export "${var}"
done

# Check required and mutually exclusive envvars
if [ -z "${REPLACES}" ] && [ -z "${SKIP_RANGE}" ]; then
  echo "one of REPLACES or SKIP_RANGE envvar is expected"
  exit 1
fi

if [ -n "${REPLACES}" ] && [ -n "${SKIP_RANGE}" ]; then
  echo "only one of REPLACES or SKIP_RANGE envvar can be set"
  exit 1
fi

# Upstream bundle dir
SOURCE_BUNDLE_DIR="${UPSTREAM_BUNDLE_DIR:-.}"
# Output bundle dir with autogenerated bundles
OUTPUT_DIR="${DOWNSTREAM_BUNDLE_DIR:-$__dir}"

# Clean up
# Useful to delete existing files not longer needed.
if [ -d "$OUTPUT_DIR" ]; then rm -Rf $OUTPUT_DIR/manifests; rm -Rf $OUTPUT_DIR/bundle; rm -Rf $OUTPUT_DIR/metadata; fi
mkdir -p $OUTPUT_DIR

tree
cp -vr "$SOURCE_BUNDLE_DIR/manifests" "$OUTPUT_DIR/"
mv "$OUTPUT_DIR/manifests" "$OUTPUT_DIR/bundle"
cp -vr "$SOURCE_BUNDLE_DIR/metadata" "$OUTPUT_DIR"

# Using ${YQ} 4.8 in development

# metadata/annotations.yaml
ANNOTATIONS_RESOURCE=$OUTPUT_DIR/metadata/annotations.yaml
${YQ} eval '.annotations."operators.operatorframework.io.bundle.channels.v1" = strenv(CHANNEL)' -i $ANNOTATIONS_RESOURCE
${YQ} eval '.annotations."operators.operatorframework.io.bundle.channel.default.v1" = strenv(CHANNEL)' -i $ANNOTATIONS_RESOURCE
${YQ} eval '.annotations."com.redhat.openshift.versions" = "v4.6"' -i $ANNOTATIONS_RESOURCE
${YQ} eval 'del(.annotations."operators.operatorframework.io.test.config.v1")' -i $ANNOTATIONS_RESOURCE
${YQ} eval 'del(.annotations."operators.operatorframework.io.test.mediatype.v1")' -i $ANNOTATIONS_RESOURCE

# bundle/3scale-operator.clusterserviceversion.yaml
CSV_RESOURCE=$OUTPUT_DIR/bundle/3scale-operator.clusterserviceversion.yaml
${YQ} eval '.metadata.annotations.containerImage = strenv(OPERATOR_CONTAINER_IMAGE)' -i $CSV_RESOURCE
${YQ} eval '.metadata.annotations.description = strenv(METADATA_DESCRIPTION)' -i $CSV_RESOURCE
${YQ} eval '.metadata.annotations."operators.openshift.io/valid-subscription" = strenv(VALID_SUBSCRIPTION)' -i $CSV_RESOURCE
${YQ} eval '.metadata.name = strenv(NAME)' -i $CSV_RESOURCE
if [ -n "${SKIP_RANGE}" ]; then
  export SKIP_RANGE
  ${YQ} eval '.metadata.annotations."olm.skipRange" = strenv(SKIP_RANGE)' -i $CSV_RESOURCE
  ${YQ} eval 'del(.spec.replaces)' -i $CSV_RESOURCE
fi
DESCRIPTION=$(cat "$__dir/DESCRIPTION") ${YQ} eval '.spec.description = strenv(DESCRIPTION)' -i $CSV_RESOURCE
${YQ} eval '.spec.displayName = strenv(DISPLAY_NAME)' -i $CSV_RESOURCE
ICON=$(cat "$__dir/ICON") ${YQ} eval '.spec.icon[0].base64data = strenv(ICON)' -i $CSV_RESOURCE
${YQ} eval '.spec.icon[0].mediatype = "image/svg+xml"' -i $CSV_RESOURCE
# TODO: improve with ${YQ} select to match component name with value. For instance: select env for backend image by name to set backend image value
${YQ} eval '.spec.install.spec.deployments[0].spec.template.spec.containers[0].env[1].value = strenv(BACKEND_IMAGE)' -i $CSV_RESOURCE
${YQ} eval '.spec.install.spec.deployments[0].spec.template.spec.containers[0].env[2].value = strenv(APICAST_IMAGE)' -i $CSV_RESOURCE
${YQ} eval '.spec.install.spec.deployments[0].spec.template.spec.containers[0].env[3].value = strenv(SYSTEM_IMAGE)' -i $CSV_RESOURCE
${YQ} eval '.spec.install.spec.deployments[0].spec.template.spec.containers[0].env[4].value = strenv(ZYNC_IMAGE)' -i $CSV_RESOURCE
${YQ} eval '.spec.install.spec.deployments[0].spec.template.spec.containers[0].env[5].value = strenv(MEMCACHED_IMAGE)' -i $CSV_RESOURCE
# Backend redis image
${YQ} eval '.spec.install.spec.deployments[0].spec.template.spec.containers[0].env[6].value = strenv(REDIS_5_IMAGE)' -i $CSV_RESOURCE
# System redis image
${YQ} eval '.spec.install.spec.deployments[0].spec.template.spec.containers[0].env[7].value = strenv(REDIS_5_IMAGE)' -i $CSV_RESOURCE
${YQ} eval '.spec.install.spec.deployments[0].spec.template.spec.containers[0].env[8].value = strenv(MYSQL_8_IMAGE)' -i $CSV_RESOURCE
# system postgresql image
${YQ} eval '.spec.install.spec.deployments[0].spec.template.spec.containers[0].env[9].value = strenv(POSTGRESQL_10_IMAGE)' -i $CSV_RESOURCE
# zync postgresql image
${YQ} eval '.spec.install.spec.deployments[0].spec.template.spec.containers[0].env[10].value = strenv(POSTGRESQL_10_IMAGE)' -i $CSV_RESOURCE
${YQ} eval '.spec.install.spec.deployments[0].spec.template.spec.containers[0].env[11].value = strenv(OC_CLI_IMAGE)' -i $CSV_RESOURCE
${YQ} eval '.spec.install.spec.deployments[0].spec.template.spec.containers[0].image = strenv(OPERATOR_CONTAINER_IMAGE)' -i $CSV_RESOURCE
${YQ} eval '.spec.links[0].name = "GitHub"' -i $CSV_RESOURCE
${YQ} eval '.spec.links[0].url = "https://github.com/3scale/3scale-operator"' -i $CSV_RESOURCE
${YQ} eval '.spec.links[1].name = "Documentation"' -i $CSV_RESOURCE
${YQ} eval '.spec.links[1].url = strenv(DOC_URL)' -i $CSV_RESOURCE
${YQ} eval '.spec.maturity = strenv(MATURITY)' -i $CSV_RESOURCE
${YQ} eval '.spec.provider.name= strenv(PROVIDER_NAME)' -i $CSV_RESOURCE
${YQ} eval '.spec.version = strenv(CSV_VERSION)' -i $CSV_RESOURCE
if [ -n "${REPLACES}" ]; then
  export REPLACES
  ${YQ} eval '.spec.replaces = strenv(REPLACES)' -i $CSV_RESOURCE
  ${YQ} eval 'del(.metadata.annotations."olm.skipRange")' -i $CSV_RESOURCE
fi
# Intentionally unset the relatedImages array to ensure no matter what is
# in upstream, we do not set the section as so digest pinning OSBS mechanism is run
# issues when additions/removals are performed. This means we ignore previously existing
# values and we set the ones we specify here
${YQ} eval 'del(.spec.relatedImages)' -i $CSV_RESOURCE
# Pretty print the array to have consistent formatting everywhere
${YQ} eval --prettyPrint -i $CSV_RESOURCE
