#!/bin/bash

# Read constants.js into a variable
constantsFile="app/js/constants.js"
constantsContent=$(<"$constantsFile")

# Extract all apiUrl options from constants.js
apiUrlOptions=($(grep -oP "apiUrl: '\K[^']+" "$constantsFile"))

# Display the apiUrl options and prompt the user to select one
echo "Available apiUrl options:"
for ((i = 0; i < ${#apiUrlOptions[@]}; i++)); do
    echo "$((i + 1)). ${apiUrlOptions[i]}"
done

read -p "Enter the number of the apiUrl option to select: " selectedOption

# Validate user input
if ! [[ "$selectedOption" =~ ^[0-9]+$ ]]; then
    echo "Error: Invalid input. Please enter a number."
    exit 1
fi

if ((selectedOption < 1 || selectedOption > ${#apiUrlOptions[@]})); then
    echo "Error: Invalid option number. Please enter a valid number."
    exit 1
fi

# Comment out all apiUrl lines except the selected one
for apiUrlOption in "${apiUrlOptions[@]}"; do
    
    #comment the active line
    constantsContent=$(sed "s|\([^/]\)apiUrl: '$apiUrlOption'|//apiUrl: '$apiUrlOption'|" <<< "$constantsContent")

    if [[ "${apiUrlOption}" == "${apiUrlOptions[selectedOption - 1]}" ]]; then
        constantsContent=$(sed "s|/\+apiUrl: '$apiUrlOption'|apiUrl: '$apiUrlOption'|" <<< "$constantsContent")
    else
        constantsContent=$(sed "s|/\+apiUrl: '$apiUrlOption'|//apiUrl: '$apiUrlOption'|" <<< "$constantsContent")

    fi
done

# Write the updated content back to constants.js
echo "$constantsContent" > "$constantsFile"
echo "Selected apiUrl (${apiUrlOptions[selectedOption - 1]}) updated in constants.js"
