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

# Public install endpoint (cli.dodil.io serves the binaries baked into the image).
# Override with DODIL_CLI_BASE_URL for testing against a PR image / local proxy.
DOWNLOAD_REPO_URL="${DODIL_CLI_BASE_URL:-https://cli.dodil.io}"

# Helper function to print messages
info() {
    echo -e "\033[34m==>\033[0m $1"
}

error() {
    echo -e "\033[31m==> ERROR:\033[0m $1" >&2
    exit 1
}

# Determine OS
OS="$(uname -s)"
case "${OS}" in
    Linux*)     OS_NAME="linux";;
    Darwin*)    OS_NAME="darwin";;
    *)          error "Unsupported OS: ${OS}";;
esac

# Determine Architecture
ARCH="$(uname -m)"
case "${ARCH}" in
    x86_64|amd64) ARCH_NAME="amd64";;
    aarch64|arm64) ARCH_NAME="arm64";;
    i386|i686)    ARCH_NAME="386";;
    *)            error "Unsupported architecture: ${ARCH}";;
esac

info "Detected OS: ${OS_NAME}"
info "Detected Architecture: ${ARCH_NAME}"

# Construct the binary name
BIN_NAME="dodil-${OS_NAME}-${ARCH_NAME}"
if [ "${OS_NAME}" = "windows" ]; then
    BIN_NAME="${BIN_NAME}.exe"
fi

BIN_URL="${DOWNLOAD_REPO_URL}/${BIN_NAME}"

# Determine installation directory
INSTALL_DIR="${HOME}/.local/bin"
EXE_PATH="${INSTALL_DIR}/dodil"

mkdir -p "${INSTALL_DIR}"

info "Downloading ${BIN_NAME} from ${BIN_URL}..."

if command -v curl >/dev/null 2>&1; then
    curl -fSL -o "${EXE_PATH}" "${BIN_URL}" || error "Download failed: ${BIN_URL}"
elif command -v wget >/dev/null 2>&1; then
    wget -qO "${EXE_PATH}" "${BIN_URL}" || error "Download failed: ${BIN_URL}"
else
    error "Neither curl nor wget was found. Please install one of them to proceed."
fi

chmod +x "${EXE_PATH}"

info "Successfully installed dodil to ${EXE_PATH}"

# Check if INSTALL_DIR is in PATH
if [[ ":$PATH:" != *":${INSTALL_DIR}:"* ]]; then
    echo ""
    info "Note: ${INSTALL_DIR} is not currently in your PATH."
    info "You may need to add the following line to your ~/.bashrc, ~/.zshrc, or ~/.profile:"
    echo "    export PATH=\"\$HOME/.local/bin:\$PATH\""
    echo ""
fi

info "Run 'dodil --help' to get started."
