#!/bin/bash 
# Info: Prepare for oci-reg installation
# Author: JesusPerezLorenzo 
# Release: 1.0.2
# Date: 15-01-2024

set +o errexit
set +o pipefail

SETTINGS_FILE=$1
SERVICE_NAME=$2
SERVICE_POS=$3
#SETTINGS_ROOT=$4
RUN_ROOT=$(dirname "$0")
#ORG=$(pwd)

[ -z "$SETTINGS_FILE"  ] && [ -z "$SERVICE_NAME" ] && [ -z "$SERVICE_POS" ] && exit 0

YQ=$(type -P yq)
JQ=$(type -P jq)
[ -z "$YQ" ] && echo "yq not installed " && exit 1
[ -z "$JQ" ] && echo "jq not installed " && exit 1

_fix_name_in_files() {
  local source=$1
  local name_in_file=$2
  local new_name
  for item in  "$source"/*
  do
    if [ -d "$item" ] ; then   
      _fix_name_in_files "$item" "$name_in_file" 
    elif [ -r "$item" ] ; then   
      new_name=$(basename "$item" | sed "s,deploy,$name_in_file,g")
      #[ -r "$(dirname "$item")/$new_name" ] && rm -f "$item" 
      [ -r "$item" ] && [ "$(basename "$item")" != "$new_name" ] && mv "$item" "$(dirname "$item")/$new_name"
    fi
  done
}

[ -r "$RUN_ROOT/env-oci-reg" ] && . "$RUN_ROOT"/env-oci-reg

[ -z "$PROVISIONING" ]  && echo "PROVISIONING not found in environment" && exit 1

. "$PROVISIONING"/core/lib/sops

if $YQ e -o=json '.service.config' < "$SETTINGS_FILE" | tee "$RUN_ROOT/config.json" >/dev/null; then
  echo "zot config.json generated !" 
else
  echo "Error: zot config.json generation !" 
  exit 1
fi
prxy=$($YQ -er '.k8s_deploy.prxy' < "$SETTINGS_FILE" 2>/dev/null | sed 's/ //g' | sed 's/null//g')
case "$prxy" in 
  istio) ;;
  *) [ -f "$RUN_ROOT/make_istio-system_secret.sh.j2" ] && rm -f "$RUN_ROOT/make_istio-system_secret.sh.j2"
esac
name_in_files=$($YQ -er '.k8s_deploy.name_in_files' < "$SETTINGS_FILE" 2>/dev/null | sed 's/ //g' | sed 's/null//g')
[ -n "$name_in_files" ] && _fix_name_in_files "$RUN_ROOT" "$name_in_files"

if [ -r "$RUN_ROOT/configMap-etc.yaml.j2" ] ; then 
  if [ -r "$RUN_ROOT/htpasswd" ] ; then 
    echo "  htpasswd: | " >> "$RUN_ROOT/configMap-etc.yaml.j2"
    sed 's,^,    ,g' <"$RUN_ROOT/htpasswd"  >> "$RUN_ROOT/configMap-etc.yaml.j2"
    rm -f "$RUN_ROOT/htpasswd"
    echo "htpasswd added to configMap-etc.yaml" 
  fi
  if [ -r "$RUN_ROOT/config.json" ] ; then 
    echo "  config.json: | " >> "$RUN_ROOT/configMap-etc.yaml.j2"
    sed 's,^,    ,g' <"$RUN_ROOT/config.json"  >> "$RUN_ROOT/configMap-etc.yaml.j2"
    rm -f "$RUN_ROOT/config.json"
    echo "zot config.json added to configMap-etc.yaml" 
  fi
fi
echo "Prepare $SERVICE_NAME $SERVICE_POS Done !" 