#!/bin/bash

current_branch=$(git symbolic-ref --short HEAD)

if [ "$current_branch" = "DevOps" ]; then
    if [ "$SVC_NAME" = "saferx-backend" ]; then

        # Your target IP address
        target_ip=$(aws ssm get-parameter --name "/$ENV_NAME/network/nat" --region us-east-1 --with-decryption --output json | jq -r '.Parameter.Value' || true)

        # JSON file
        json_file=".github/env_files/saferx-backend/dev/$ENV_NAME.json"

        # Read the JSON file into a variable
        json_data=$(cat "$json_file")

        # Extract the value of "SX_SSHD_DIRECT_ACCESS" key
        ssh_direct_access=$(echo "$json_data" | jq -r '.SX_SSHD_DIRECT_ACCESS')

        # Check if the target IP is in the list
        if echo "$ssh_direct_access" | grep -q "\<$target_ip\>"; then
            echo "$target_ip is already in the SX_SSHD_DIRECT_ACCESS list."
        else
            # Add the target IP to the list
            updated_ips="${ssh_direct_access},${target_ip}"

            # Update the JSON data with the new list
            updated_json=$(echo "$json_data" | jq ".SX_SSHD_DIRECT_ACCESS=\"$updated_ips\"")

            # Save the updated JSON data back to the file
            echo "$updated_json" > "$json_file"
            echo "Added $target_ip to SX_SSHD_DIRECT_ACCESS list."
        fi

        #### setting nomad server ip

        # Check if the Nomad server IP is in the list
        nomad_ip=$(aws ssm get-parameter --name "/$ENV_NAME/network/NOMAD_IP" --region us-east-1 --with-decryption --output json | jq -r '.Parameter.Value' || true)
        updated_json=$(cat "$json_file")
        updated_json=$(echo "$updated_json" | jq ".SX_NOMAD_SERVERS=\"$nomad_ip\"")

        # Save the updated JSON data back to the file
        echo "$updated_json" > "$json_file"
        echo "Replaced SX_NOMAD_SERVERS with $nomad_ip."



        echo "pushing the new ips"
        git config --global user.email "svc-github@perimeter81.com"
        git config --global user.name "Sayuser"
        git add "$json_file"
        git commit -m "updated the ip in $ENV_NAME.json"
        git push origin DevOps

    else
        echo "SVC_NAME is not 'saferx-backend'."
    fi
else
    echo "Current branch ('$current_branch') is not 'DevOps'."
fi
