#!/bin/bash -e
#
# $2 is the install location
#
SNOWFLAKE_CLI_COMMENT="# added by Snowflake SnowflakeCLI installer v1.0"
RC_FILES=(~/.zprofile ~/.zshrc ~/.profile ~/.bash_profile ~/.bashrc)

function add_dest_path_to_profile() {
  local dest=$1
  local profile=$2
  echo "Updating $profile to have $dest in PATH"
  touch $profile
  cp -p $profile "$profile-snowflake.bak" || true
  echo "
$SNOWFLAKE_CLI_COMMENT
export PATH=$dest:\$PATH" >>$profile
}

echo "[DEBUG] Parameters: $1 $2"
SNOWFLAKE_CLI_DEST=$2/SnowflakeCLI.app/Contents/MacOS/

# List of potential login shell RC files

# Check if the path is already in the PATH variable
if [[ ":$PATH:" == *":$SNOWFLAKE_CLI_DEST:"* ]]; then
  echo "[INFO] Path $SNOWFLAKE_CLI_DEST is already in PATH. No changes needed."
else
  for rc_file in "${RC_FILES[@]}"; do
    # Expand tilde (~) to the user's home directory
    rc_file_expanded=$(eval echo "$rc_file")

    if [[ -e "$rc_file_expanded" ]]; then
      # Add the PATH update to the file
      add_dest_path_to_profile "$SNOWFLAKE_CLI_DEST" "$rc_file_expanded"
    else
      echo "[INFO] $rc_file_expanded does not exist, skipping..."
    fi
  done
fi
