#! /bin/bash

# Change the current directory to the script directory
BASEDIR=$(dirname "$0")
cd $BASEDIR

# Look for the .env file
while [[ "$PWD" != "$HOME" && ! -e .env ]]; do cd ..; done
if [[ ! -e .env ]]; then
  echo "CANCELED"
  echo "  No .env file found in the directory tree."
  echo "  Please setup the .env file and retry"
  exit 1
fi

ENVFILEDIR=$PWD
set -a; source .env; set +a

echo "Select the variable to replace:"
options=("smtpKey" "smtpSecret" "awsAccessKeyId" "awsSecretAccessKey" "other")
select var_choice in "${options[@]}"; do
  case $var_choice in
    "other")
      read -p "Enter the variable name: " var_name
      break
      ;;
    "smtpKey"|"smtpSecret"|"awsAccessKeyId"|"awsSecretAccessKey")
      var_name=$var_choice
      break
      ;;
    *)
      echo "Invalid choice. Try again."
      ;;
  esac
done

# SSH into the server and retrieve the current value of the variable
current_value=$(ssh -i "$pem_path" "$api_user@$bastion_server" ssh "$api_user@$api_server" << EOF
    sudo -u "$api_suuser" bash -c '
        cd \$HOME
        while [[ "\$PWD" != "\$HOME" && ! -e .env ]]; do cd ..; done
        [[ -e .env ]] && grep "^$var_name=" .env | cut -d'=' -f2- || exit 1'
EOF
)

if [[ $? -eq 1 ]]; then
  echo "ERROR: No .env file found on the remote server."
  exit 1
fi

if [[ -z "$current_value" ]]; then
  echo "ERROR: The variable '$var_name' was not found in the remote .env file."
  echo "Please check the variable name and try again."
  exit 1
fi

echo "Variable: $var_name"
echo "Current Value: $current_value"
read -p "Enter new value for $var_name: " new_value

read -p "Are you sure you want to update this variable? (yes/no): " confirm
if [[ "$confirm" != "yes" ]]; then
  echo "Operation canceled."
  exit 1
fi

# SSH into the server and replace the variable in the .env file
ssh -i "$pem_path" "$api_user@$bastion_server" ssh "$api_user@$api_server" << EOF
    sudo -u "$api_suuser" bash -c '
        cd \$HOME
        while [[ "\$PWD" != "\$HOME" && ! -e .env ]]; do cd ..; done
        [[ ! -e .env ]] && exit 1
        grep -q "^$var_name=" .env || exit 2
        sed -i "s|^$var_name=.*|$var_name=\"$new_value\"|" .env'
EOF

# In the below, cases 1 and 2 should never happen, unless the .env file gets deleted or the contents modified while running the script
case $? in
  1)
    echo "ERROR: No .env file found in the remote directory tree."
    echo "Please setup the .env file and retry."
    exit 1
    ;;
  2)
    echo "ERROR: The variable '$var_name' does not exist in the .env file."
    exit 1
    ;;
  0)
    echo "Update completed."
    ;;
esac
