#!/usr/bin/env bash
# install.sh — SelixyHUB — Linux & macOS
# Usage : curl -fsSL https://dl.selixy.dev/selixy/install.sh | bash
# Mirror override : SELIXY_DOWNLOAD_BASE_URL=https://releases.selixy.app/selixy

set -euo pipefail

main() {
    BIN_DIR="${HOME}/.local/bin"
    BIN_NAME="selixy"

    # --- Détection plateforme --------------------------------------------------
    OS=$(uname -s | tr '[:upper:]' '[:lower:]')
    ARCH=$(uname -m)

    case "${OS}-${ARCH}" in
        linux-x86_64)   ASSET="selixy-hub-linux-x86_64"   ;;
        linux-aarch64)  ASSET="selixy-hub-linux-aarch64"  ;;
        darwin-x86_64)  ASSET="selixy-hub-macos-x86_64"   ;;
        darwin-arm64)   ASSET="selixy-hub-macos-aarch64"  ;;
        *)
            echo "Plateforme non supportée : ${OS}-${ARCH}"
            exit 1
            ;;
    esac

    if [[ -n "${SELIXY_DOWNLOAD_BASE_URL:-}" ]]; then
        IFS=',' read -r -a BASE_URLS <<< "${SELIXY_DOWNLOAD_BASE_URL}"
    else
        # dl.selixy.dev sert depuis le VPS OVH (nginx + Let's Encrypt direct,
        # root sur le sous-dossier selixy/ donc pas de /selixy/ dans l'URL).
        # releases.selixy.app sert depuis srv_selixy.app (WSL + Cloudflare
        # Tunnel) avec namespace /selixy/, fallback en cas d'indispo VPS.
        BASE_URLS=(
            "https://dl.selixy.dev"
            "https://releases.selixy.app/selixy"
        )
    fi

    # --- Téléchargement --------------------------------------------------------
    mkdir -p "${BIN_DIR}"
    downloaded=0
    for BASE_URL in "${BASE_URLS[@]}"; do
        echo "→ Téléchargement de ${ASSET} depuis ${BASE_URL}..."
        if curl -fsSL --http1.1 --retry 3 --retry-all-errors "${BASE_URL}/${ASSET}" -o "${BIN_DIR}/${BIN_NAME}"; then
            downloaded=1
            break
        fi
    done

    if [[ "${downloaded}" -ne 1 ]]; then
        echo "Impossible de télécharger ${ASSET} depuis les miroirs connus."
        exit 1
    fi
    chmod +x "${BIN_DIR}/${BIN_NAME}"

    # --- Vérification PATH -----------------------------------------------------
    if ! echo "${PATH}" | grep -q "${BIN_DIR}"; then
        echo ""
        echo "! ${BIN_DIR} n'est pas dans ton PATH."
        echo "  Ajoute cette ligne dans ~/.bashrc ou ~/.zshrc :"
        echo "    export PATH=\"${BIN_DIR}:\$PATH\""
        echo "  Puis recharge : source ~/.bashrc"
    fi

    # --- Succès ----------------------------------------------------------------
    SELIXY_VERSION=$("${BIN_DIR}/${BIN_NAME}" --version </dev/null 2>&1 || echo "installé")
    echo ""
    echo "✓ ${SELIXY_VERSION}"
    echo ""
    echo "  Lance le setup SSH :"
    echo "    selixy setup ssh"
}

main
