#!/usr/bin/env bash

# SPDX-FileCopyrightText: 2024 SAP SE or an SAP affiliate company and Gardener contributors
#
# SPDX-License-Identifier: Apache-2.0

# Configuration Options:
#
# COMPONENT_PREFIXES: Set the image prefix that should be used to
#                     determine if an image is defined by another component.
#                     Defaults to "europe-docker.pkg.dev/gardener-project/releases/gardener"
#
# COMPONENT_CLI_ARGS: Set all component-cli arguments.
#                     This should be used with care as all defaults are overwritten.
#

set -e

repo_root_dir="$1"
repo_name="${2:-github.com/gardener/gardener}"
descriptor_out_file="${COMPONENT_DESCRIPTOR_PATH}"

resources_file="$repo_root_dir/.ci/resources.yaml"
if [[ -f ${resources_file} ]]; then
  echo "Adding additional resources from ${resources_file}"

  # component-cli expects a directory where the component descriptor file is named component-descriptor.yaml.
  # however the pre-rendered component descriptors of the pipeline have different filenames.
  # therefore create a tempdir and copy the pre-rendered component descriptor to it with the correct filename.
  tmp_dir="$(mktemp -d)"
  tmp_cd="${tmp_dir}/component-descriptor.yaml"
  cp "${BASE_DEFINITION_PATH}" "${tmp_cd}"
  echo "${tmp_cd}"

  # read the component version.
  if [[ -z ${EFFECTIVE_VERSION} ]]; then
    echo "The env variable EFFECTIVE_VERSION must be set"
    exit 1
  fi

  # adds all resources defined in the resources file to the component descriptor.
  component-cli component-archive resources add ${tmp_dir} ${resources_file} -v=3 -- COMPONENT_VERSION=${EFFECTIVE_VERSION}

  # move modified component descriptor back to the original file.
  mv "${tmp_cd}" "${BASE_DEFINITION_PATH}"
else
  echo "Resources file ${resources_file} not found. Skip adding additional resources."
fi

echo "Enriching component descriptor from ${BASE_DEFINITION_PATH}"

image_vector_path=""
if [[ -f "$repo_root_dir/charts/images.yaml" ]]; then
  image_vector_path="$repo_root_dir/charts/images.yaml"
elif [[ -f "$repo_root_dir/imagevector/images.yaml" ]]; then
  image_vector_path="$repo_root_dir/imagevector/images.yaml"
elif [[ -f "$repo_root_dir/imagevector/containers.yaml" ]]; then
  image_vector_path="$repo_root_dir/imagevector/containers.yaml"
fi

if [[ ! -z "$image_vector_path" ]]; then
  # default environment variables
  if [[ -z "${COMPONENT_PREFIXES}" ]]; then
    COMPONENT_PREFIXES="europe-docker.pkg.dev/gardener-project/releases/gardener,europe-docker.pkg.dev/gardener-project/snapshots/gardener"
  fi

  if [[ -z "${COMPONENT_CLI_ARGS}" ]]; then
    COMPONENT_CLI_ARGS="
    --comp-desc ${BASE_DEFINITION_PATH} \
    --image-vector "$image_vector_path" \
    --component-prefixes "${COMPONENT_PREFIXES}" \
    "
  fi

  # translates all images defined the containers.yaml into component descriptor resources.
  # For detailed documentation see https://github.com/gardener/component-cli/blob/main/docs/reference/components-cli_image-vector_add.md
  component-cli image-vector add ${COMPONENT_CLI_ARGS}
fi

if [[ -d "$repo_root_dir/charts/" ]]; then
  for image_tpl_path in "$repo_root_dir/charts/"*"/templates/_images.tpl"; do
    if [[ ! -f "$image_tpl_path" ]]; then
      continue
    fi

    outputFile=$(sed 's/{{-//' $image_tpl_path | sed 's/}}//' | sed 's/define//' | sed 's/-//' | sed 's/end//' | sed 's/"//' | sed 's/"//' |sed 's/image.//' |  sed -e 's/^[ \t]*//' | awk -v RS= '{for (i=1; i<=NF; i++) printf "%s%s", $i, (i==NF?"\n":" ")}')
    echo "enriching component descriptor from ${image_tpl_path}"

    while read p; do
      line="$(echo -e "$p")"
      IFS=' ' read -r -a array <<< "$line"
      IFS=': ' read -r -a imageAndTag <<< ${array[1]}

      NAME=${array[0]}
      REPOSITORY=${imageAndTag[0]}
      TAG=${imageAndTag[1]}

      ${ADD_DEPENDENCIES_CMD} --container-image-dependencies "{\"name\": \"${NAME}\", \"image_reference\": \"${REPOSITORY}:${TAG}\", \"version\": \"$TAG\"}"
    done < <(echo "$outputFile")
  done
fi

cp "${BASE_DEFINITION_PATH}" "${descriptor_out_file}"
