#!/usr/bin/env bash
set -euo pipefail

usage() {
    cat <<'EOF'
Usage: install_miniconda [-h|--help]

Downloads and installs Miniconda into ~/miniconda3 (interactive-ish).

Notes:
  - This script is primarily intended for Linux/macOS environments.
  - It does not require a repo checkout; it can be run from packaged resources.
EOF
}

detect_machine() {
    local system arch

    system="$(uname -s)"
    arch="$(uname -m)"

    case "${system}:${arch}" in
        Darwin:arm64)
            printf '%s\n' "apple_silicon"
            ;;
        Darwin:x86_64)
            printf '%s\n' "intel_mac"
            ;;
        Linux:arm64|Linux:aarch64)
            printf '%s\n' "linux_arm"
            ;;
        Linux:x86_64)
            printf '%s\n' "linux_x86"
            ;;
        *)
            return 1
            ;;
    esac
}

download_file() {
    local url="$1"
    local output_path="$2"

    if command -v curl >/dev/null 2>&1; then
        if curl -fsSL "$url" -o "$output_path"; then
            return 0
        fi
    fi

    if command -v wget >/dev/null 2>&1; then
        wget -q "$url" -O "$output_path"
        return 0
    fi

    echo "Neither curl nor wget is available for downloading ${url}."
    return 1
}

copy_conda_block() {
    local source_file="$1"
    local target_file="$2"
    local conda_block

    conda_block="$(sed -n '/# >>> conda initialize >>>/,/# <<< conda initialize <<</p' "$source_file")"

    echo "Adding Conda initialization block to $target_file."
    printf '\n' >> "$target_file"
    printf '%s\n' "$conda_block" >> "$target_file"
    echo "Conda initialization block added to $target_file."
}

main() {
    local installer_url=""
    local installer_script=""
    local installer_label=""
    local conda_bin=""
    local bashrc bash_profile
    local bashrc_has_block=false
    local bash_profile_has_block=false

    if [[ "${1:-}" == "-h" || "${1:-}" == "--help" ]]; then
        usage
        exit 0
    fi

    if command -v conda >/dev/null 2>&1; then
        conda_bin="$(command -v conda)"
        echo "Miniconda/Conda is already installed. Ensuring shell initialization is present."
    elif [[ -x "$HOME/miniconda3/bin/conda" ]]; then
        conda_bin="$HOME/miniconda3/bin/conda"
        echo "Miniconda is already installed at $HOME/miniconda3. Ensuring shell initialization is present."
    else
        echo "Miniconda is not installed. Proceeding with installation..."
    fi

    if [[ -z "$conda_bin" ]]; then
        if [[ -z "${MACHINE:-}" ]]; then
            MACHINE="$(detect_machine)" || {
                echo "Unsupported system/architecture: $(uname -s) $(uname -m)"
                exit 1
            }
        fi

        case "$MACHINE" in
            apple_silicon)
                installer_label="Apple Silicon"
                installer_url="https://repo.anaconda.com/miniconda/Miniconda3-latest-MacOSX-arm64.sh"
                installer_script="Miniconda3-MacOSX-arm64.sh"
                ;;
            intel_mac)
                installer_label="Intel Mac"
                installer_url="https://repo.anaconda.com/miniconda/Miniconda3-latest-MacOSX-x86_64.sh"
                installer_script="Miniconda3-MacOSX-x86_64.sh"
                ;;
            linux_x86)
                installer_label="Linux x86"
                installer_url="https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh"
                installer_script="Miniconda3-Linux-x86_64.sh"
                ;;
            linux_arm)
                installer_label="Linux ARM"
                installer_url="https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-aarch64.sh"
                installer_script="Miniconda3-Linux-aarch64.sh"
                ;;
            *)
                echo "Unsupported machine type: $MACHINE"
                echo "Please visit https://docs.conda.io/en/latest/miniconda.html for manual installation instructions."
                exit 2
                ;;
        esac

        echo "Autoinstalling Miniconda for ${installer_label}..."
        download_file "$installer_url" "$installer_script"
        chmod +x "$installer_script"
        "./$installer_script" -b -p "$HOME/miniconda3"
        rm -f "$installer_script"
        conda_bin="$HOME/miniconda3/bin/conda"
    fi

    if [[ -x "$conda_bin" ]]; then
        echo "Initializing Conda..."
        "$conda_bin" init bash
        "$conda_bin" init zsh

        bashrc="$HOME/.bashrc"
        bash_profile="$HOME/.bash_profile"

        touch "$bashrc" "$bash_profile"

        if grep -q "# >>> conda initialize >>>" "$bashrc"; then
            bashrc_has_block=true
        fi

        if grep -q "# >>> conda initialize >>>" "$bash_profile"; then
            bash_profile_has_block=true
        fi

        if $bashrc_has_block && ! $bash_profile_has_block; then
            echo "Conda initialization block found in .bashrc but missing in .bash_profile."
            copy_conda_block "$bashrc" "$bash_profile"
        elif $bash_profile_has_block && ! $bashrc_has_block; then
            echo "Conda initialization block found in .bash_profile but missing in .bashrc."
            copy_conda_block "$bash_profile" "$bashrc"
        elif $bashrc_has_block && $bash_profile_has_block; then
            echo "Conda initialization block already exists in both .bashrc and .bash_profile. No changes made."
        else
            echo "No Conda initialization block found in either .bashrc or .bash_profile."
            echo "From a bash shell, please run 'conda init bash' to initialize Conda."
            exit 1
        fi

        echo "Miniconda installation successful."
        echo "Open a new shell, and conda should be available (try: 'conda -v')."
    else
        echo "Miniconda installation failed. Please try again and/or atttempt the commands in this script manually."
        exit 3
    fi
}

if [[ "${BASH_SOURCE[0]}" == "$0" ]]; then
    main "$@"
fi
