#!/bin/bash

set -e

base_url="git@github.com:perimeter-81/"

export GIT_TOKEN=$GLOBAL_CICD_GIT_TOKEN

backend_yaml_file1=".github/workflows/update_env_and_ecs.yaml"
backend_yaml_file2=".github/workflows/build(and_deploy).yaml"
core_yaml_file=".github/workflows/build_and_deploy_or_just_deploy.yaml"
saferx_backend_env_file=".github/env_files/saferx-backend/dev/$ENV_NAME.json"
common_files_path=".github/workflows/restart_all_ecs_microservices.yaml"

list_core=$(cat repos.yaml | grep ':\s*{.*}$' | grep "core-ecs" | cut -d " " -f1)
list_frontend=("webclient" "workspace")
list_backend=$(cat repos.yaml | grep ':\s*{.*}$' | grep " backend" | grep -v "devops-assesmnt" | grep -v "cd-poc-" | cut -d " " -f1)

echo core repos: $list_core
echo frontend repos: "${list_frontend[@]}"
echo backend repos: $list_backend

git config --global user.email "svc-github@perimeter81.com"
git config --global user.name "Sayuser"

echo test access
git clone $base_url"CD-Process-POC1.git"
echo access granted

update_yaml() {
    local repo=$1
    local yaml_file=$2

    if grep -q "$ENV_NAME" "$yaml_file"; then
        echo "Name '$ENV_NAME' already exists in the file. Nothing to do."
    else
        echo "Name '$ENV_NAME' does not exist in the file. Adding it."
        new_yaml=$(yq eval '.on.workflow_dispatch.inputs.ENV_NAME.options += ["'"$ENV_NAME"'"]' "$yaml_file")
        echo "$new_yaml" > "$yaml_file"
        echo "Name '$ENV_NAME' added to the file."
        echo "pushing the new env to the repo"
        git add "$yaml_file"
        git commit -m "updated the allowed envs in the repo $repo"
        git push origin DevOps
    fi
}

clone_and_update() {
    local repo=$1
    local yaml_files=("${@:2}")

    echo "pulling repo $repo"
    git clone $base_url$repo
    cd $repo
    git checkout DevOps

    for yaml_file in "${yaml_files[@]}"; do
        update_yaml $repo $yaml_file
    done

    cd ..
}

echo "BACKEND"
for ms in $list_backend; do
    clone_and_update $ms "$backend_yaml_file1" "$backend_yaml_file2"
done

echo "CORE"
for ms in $list_core; do
    clone_and_update $ms "$core_yaml_file"
    if [ "$ms" = "saferx" ]; then
        if [ ! -f "$saferx_backend_env_file" ]; then
            echo "also copying the template file"
            cp .github/env_files/saferx-backend/dev/template.json "$saferx_backend_env_file"
            git add "$saferx_backend_env_file"
            echo "pushing the new env.json to the repo"
            git add "$saferx_backend_env_file"
            git commit -m "updated the allowed envs in the core repo $ms"
            git push origin DevOps
        fi
    fi
done

echo "FRONTEND"
for ms in "${list_frontend[@]}"; do
    clone_and_update "perimeter81-$ms" ".github/workflows/$ms.yaml"
done

echo "COMMON FILES"
clone_and_update "common_files" "$common_files_path"
