#!/usr/bin/env bash

DEST=${1:-/etc/skel}
set -x

# Repository Configuration
URL="repo.anaconda.com"
TRANSPORT="https"
URI="${URL}/pkgs/misc/debrepo/conda"
TYPES=(deb)
SUITES="stable"
COMPONENTS=(main)
ARCHITECTURES=(amd64)

# Key Configuration
KEY_DIR="/usr/share/keyrings"
KEY_NAME="conda-archive-keyring.gpg"
KEY_PATH="${KEY_DIR}/${KEY_NAME}"
GPG_KEY_URL="https://repo.anaconda.com/pkgs/misc/gpgkeys/anaconda.asc"
FINGERPRINT="34161F5BF5EB1D4BFBBB8F0A8AEB4F8B29D82806"

# Package Configuration
packages=(conda)

## --- Functions ---

conf_print_conda_sources() {
  cat <<EOF
Enabled: yes
Types: ${TYPES[*]}
URIs: ${TRANSPORT}://${URI}
Suites: ${SUITES}
Components: ${COMPONENTS[*]}
Architectures: ${ARCHITECTURES[*]}
Signed-By: ${KEY_PATH}
EOF
}

## --- Execution ---

# 1. Install GPG Key
curl -fsSL "${GPG_KEY_URL}" | gpg --dearmor | sudo tee "${KEY_PATH}" >/dev/null
sudo chmod 644 "${KEY_PATH}"

# 2. Verify Fingerprint
if ! gpg --keyring "${KEY_PATH}" --no-default-keyring --fingerprint "${FINGERPRINT}" >/dev/null 2>&1; then
  echo "Error: GPG Fingerprint mismatch!"
  exit 1
fi

# 3. Create deb822 Sources file
conf_print_conda_sources | sudo tee /etc/apt/sources.list-available/conda.sources >/dev/null
sudo ln -sf /etc/apt/sources.list-available/conda.sources /etc/apt/sources.list.d/conda.sources

# 4. Proxy Bypass Logic
PROXY_FILE="/etc/apt/apt.conf.d/02proxy"
ENTRY="Acquire::http::Proxy { \"${URL}\" DIRECT; };"

if [ -f "$PROXY_FILE" ] && grep -qF "${URL}" "$PROXY_FILE"; then
  echo "Proxy bypass for ${URL} is already present."
else
  echo "$ENTRY" | sudo tee -a "$PROXY_FILE" >/dev/null
fi

# 5. Install Conda
sudo apt update
sudo apt install -y "${packages[@]}"

# 6. Zsh Configuration Template
mkdir -p "${DEST}"/.zshrc.pre-plugins.d/

conf_print_zsh_conda_pre() {
  cat <<-EOF
    # when using conda from the vim plugin it expects to be called from base conda environment.
    ## >>> conda initialize >>>
    ## !! Contents within this block are managed by 'conda init' !!
    __conda_setup="$('/opt/conda/bin/conda' 'shell.zsh' 'hook' 2>/dev/null)"
    if [ $? -eq 0 ]; then
        eval "\$__conda_setup"
    else
        if [ -f "/opt/conda/etc/profile.d/conda.sh" ]; then
            . "/opt/conda/etc/profile.d/conda.sh"
        else
            export PATH="/opt/conda/bin:\$PATH"
        fi
    fi
    unset __conda_setup
    ## <<< conda initialize <<<

    # switch to the default conda environment when leaving a condaenv
    AUTOSWITCH_DEFAULT_CONDAENV="base"
EOF
}
# Now managed by mise
# conf_print_zsh_conda_pre | tee "${DEST}"/.zshrc.pre-plugins.d/008_conda.zsh >/dev/null

# 7. Verification
# Note: Using 'command' to ensure we use the newly installed binary path if not in current shell PATH
if [ -f "/opt/conda/etc/profile.d/conda.sh" ]; then
  . /opt/conda/etc/profile.d/conda.sh
  conda -V
fi
