#!/usr/bin/env bash
#
# SPDX-FileCopyrightText: SAP SE or an SAP affiliate company and Gardener contributors
#
# SPDX-License-Identifier: Apache-2.0

# Please note:
# This script is only relevant for the local deployment with the operator and when using the Skaffold config `skaffold.yaml` or `skaffold-operator.yaml`.

# This script aims to solve the problem described in: https://github.com/gardener/gardener/issues/10209
# Both Skaffold configuration files, `skaffold.yaml` and `skaffold-operator.yaml`, generate dynamic patch files for Kustomize by invoking the following script through `build.hooks.after.command` lifecycle hooks:
# `dev-setup/gardenlet/base/generate-patch-gardenlet.sh`
# Since the patch files are not checked into the repository they are generated after Skaffold has built the artifacts.
# However, by default, Skaffold caches artifacts and does not rebuild them if the source files have not changed.
# Skaffold does not invoke build lifecycle hooks if the artifacts are cached.
# As part of the local deployment Kustomize is invoked to apply the patches generated by the script.
# If, for whatever reason, the patch files are not generated, Kustomize will fail to apply the patches and break the deployment.
# This script is a workaround that checks whether the patch files exist and that they contain the expected version pattern.
# It returns a literal boolean value to be passed to Skaffold's `--cache-artifacts` CLI flag.

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

# The files below are generated by both `skaffold.yaml` and `skaffold-operator.yaml`.
patch_files=(
  "dev-setup/gardenlet/base/patch-helm-ref.yaml"
  "dev-setup/gardenlet/base/patch-imagevector-overwrite.yaml"
)

scenario="${1:-}"

if [[ "$scenario" == "gardenadm" ]]; then
  # The file below is generated by `skaffold-gardenadm.yaml`.
  patch_files=(
    "dev-setup/gardenadm/resources/generated/.imagevector-overwrite.yaml"
    "dev-setup/gardenadm/resources/generated/.imagevector-overwrite-charts.yaml"
  )
fi

# The patch files should contain the Gardener version and the Git commit SHA.
gardener_version=$(cat "VERSION")
git_abbrev_commit_sha=$(git rev-parse --short=10 HEAD)

# Iterate over all patch files and check for their existence.
for patch_file in "${patch_files[@]}"; do
  # Check if the patch file contains the expected version pattern: `<Gardener version>-<Git commit abbreviated SHA>` -> e.g. `v1.113.0-dev-215797c884`.
  # The gardenadm image references use an unpredictable, full 64 character hash, e.g. `v1.120.0-dev-d31a82d927f943360a385ea5d646bb61ddf6996183ebbe3a614a800556934dbc`.
  if ! grep -q -E "(tag: |ref: .+)$gardener_version-($git_abbrev_commit_sha|[a-z0-9]{64}$)" "$patch_file"; then
    # The patch file does not exist or does not contain the expected version pattern.
    # Skaffold should not cache artifacts.
    echo "false"
    exit 0
  fi
done

# Skaffold should cache artifacts.
echo "true"
exit 0
