#!/bin/bash
# Usage: ./customize.sh dev|qa|prod
echo "tetst" $IMAGE_TAG_backend
ENV=$1
VALUES_DIR="env/$ENV"
PROPERTIES_FILE="properties.env"
YAML_DIR="kubernetes"

# Estrai l'hash completo del commit e crea una variabile temporanea per la sostituzione
TAG=$(git rev-parse HEAD)
TMP_TAG_FILE=$(mktemp)
TMP_VALUES_FILE=$(mktemp)
echo "TAG=$TAG" > "$TMP_TAG_FILE"
cat ./imglist >> "$TMP_TAG_FILE"


if [ ! -d "$VALUES_DIR" ] || ! ls "$VALUES_DIR"/*.env &>/dev/null; then
  echo "Nessun file .env trovato in $VALUES_DIR"
  exit 1
fi

if [ ! -f "$PROPERTIES_FILE" ]; then
  echo "File $PROPERTIES_FILE non trovato."
  exit 1
fi

# Crea una lista key=value temporanea partendo da tutti i file *.env in env/$ENV e aggiunge env dinamico
> "$TMP_VALUES_FILE"
for env_file in "$VALUES_DIR"/*.env; do
  cat "$env_file" >> "$TMP_VALUES_FILE"
  printf '\n' >> "$TMP_VALUES_FILE"
done
printf '\nenv=%s\n' "$ENV" >> "$TMP_VALUES_FILE"

# Trova tutti i file .yaml nella directory kubernetes e sottodirectory
find "$YAML_DIR" -type f -name "*.yaml" | while read YAML_FILE; do

  while IFS='=' read -r key value; do
    sed -i "s|<$key>|$value|g" "$YAML_FILE"
  done < "$TMP_VALUES_FILE"

  while IFS='=' read -r key value; do
    sed -i "s|<$key>|$value|g" "$YAML_FILE"
  done < "$PROPERTIES_FILE"

  # Sostituzione dinamica della chiave TAG
  while IFS='=' read -r key value; do
    sed -i "s|<$key>|$value|g" "$YAML_FILE"
  done < "$TMP_TAG_FILE"

  echo "Sostituzione completata per file $YAML_FILE ambiente $ENV."
  cat $YAML_FILE
done

rm -f "$TMP_TAG_FILE" "$TMP_VALUES_FILE"
