#!/usr/bin/env bash
# install_android_sdk — Descarga e instala Android SDK command-line tools y JDK 17
# localmente (sin root/sudo) en $ANDROID_SDK_DIR (default: $HOME/android-sdk).
set -euo pipefail

install_android_sdk() {
    local sdk_dir="${ANDROID_SDK_DIR:-$HOME/android-sdk}"
    # tmp_dir es global a proposito: el trap EXIT se dispara al terminar el
    # script (fuera del scope de la funcion), donde una variable `local` ya no
    # existiria y `set -u` la marcaria como unbound. La expansion defensiva
    # ${tmp_dir:-} evita el fallo aunque el trap corra antes de la asignacion.
    tmp_dir="$(mktemp -d)"

    # Limpia temporales al salir
    trap 'rm -rf "${tmp_dir:-}"' EXIT

    # 1. Verifica si ya está instalado
    if [[ -f "$sdk_dir/cmdline-tools/latest/bin/sdkmanager" ]]; then
        if JAVA_HOME="$(ls -d "$sdk_dir"/jdk-17/jdk-17* 2>/dev/null | head -1)" \
           "$sdk_dir/cmdline-tools/latest/bin/sdkmanager" --version &>/dev/null; then
            echo "Android SDK ya instalado en: $sdk_dir"
            return 0
        fi
    fi

    mkdir -p "$sdk_dir"

    # 2. Descarga JDK 17 si no existe
    local jdk_dir
    jdk_dir="$(ls -d "$sdk_dir"/jdk-17/jdk-17* 2>/dev/null | head -1 || true)"

    if [[ -z "$jdk_dir" ]]; then
        echo "Descargando JDK 17..."
        local jdk_tar="$tmp_dir/jdk17.tar.gz"
        local jdk_url="https://api.adoptium.net/v3/binary/latest/17/ga/linux/x64/jdk/hotspot/normal/eclipse"

        if ! curl -fL --progress-bar -o "$jdk_tar" "$jdk_url"; then
            echo "ERROR: fallo al descargar JDK 17 desde $jdk_url" >&2
            return 1
        fi

        mkdir -p "$sdk_dir/jdk-17"
        echo "Extrayendo JDK 17..."
        if ! tar -xzf "$jdk_tar" -C "$sdk_dir/jdk-17"; then
            echo "ERROR: fallo al extraer JDK 17" >&2
            return 1
        fi

        jdk_dir="$(ls -d "$sdk_dir"/jdk-17/jdk-17* 2>/dev/null | head -1 || true)"
        if [[ -z "$jdk_dir" ]]; then
            echo "ERROR: no se encontro directorio jdk-17* tras la extraccion" >&2
            return 1
        fi

        if ! JAVA_HOME="$jdk_dir" "$jdk_dir/bin/java" -version &>/dev/null; then
            echo "ERROR: java -version fallo tras instalar JDK" >&2
            return 1
        fi
        echo "JDK 17 instalado: $jdk_dir"
    else
        echo "JDK 17 ya presente: $jdk_dir"
    fi

    export JAVA_HOME="$jdk_dir"

    # 3. Descarga Android cmdline-tools si no existen
    if [[ ! -f "$sdk_dir/cmdline-tools/latest/bin/sdkmanager" ]]; then
        echo "Descargando Android cmdline-tools..."
        local tools_zip="$tmp_dir/cmdline-tools.zip"
        local tools_url="https://dl.google.com/android/repository/commandlinetools-linux-11076708_latest.zip"

        if ! curl -fL --progress-bar -o "$tools_zip" "$tools_url"; then
            echo "ERROR: fallo al descargar Android cmdline-tools desde $tools_url" >&2
            return 1
        fi

        local tools_tmp="$tmp_dir/cmdline-tools-extracted"
        mkdir -p "$tools_tmp"
        echo "Extrayendo cmdline-tools..."
        if ! unzip -q "$tools_zip" -d "$tools_tmp"; then
            echo "ERROR: fallo al extraer cmdline-tools" >&2
            return 1
        fi

        # La estructura del zip es cmdline-tools/bin/..., reorganizar a cmdline-tools/latest/
        mkdir -p "$sdk_dir/cmdline-tools"
        if [[ -d "$tools_tmp/cmdline-tools" ]]; then
            mv "$tools_tmp/cmdline-tools" "$sdk_dir/cmdline-tools/latest"
        else
            echo "ERROR: estructura inesperada en el zip de cmdline-tools" >&2
            return 1
        fi

        if [[ ! -f "$sdk_dir/cmdline-tools/latest/bin/sdkmanager" ]]; then
            echo "ERROR: sdkmanager no encontrado tras extraer cmdline-tools" >&2
            return 1
        fi
        echo "cmdline-tools instalados"
    else
        echo "cmdline-tools ya presentes"
    fi

    local sdkmanager="$sdk_dir/cmdline-tools/latest/bin/sdkmanager"
    export ANDROID_HOME="$sdk_dir"
    export ANDROID_SDK_ROOT="$sdk_dir"
    export PATH="$JAVA_HOME/bin:$sdk_dir/cmdline-tools/latest/bin:$sdk_dir/platform-tools:$PATH"

    # 4. Acepta licencias e instala paquetes necesarios
    # `yes` recibe SIGPIPE (exit 141) cuando sdkmanager termina de leer y cierra
    # el pipe; bajo `set -o pipefail` eso convierte un exito real en falso
    # negativo. Desactivamos pipefail solo aqui para que el exit del pipeline
    # refleje el de sdkmanager (ultimo comando), no el SIGPIPE de `yes`.
    echo "Aceptando licencias de Android SDK..."
    set +o pipefail
    if ! yes | "$sdkmanager" --licenses >/dev/null 2>&1; then
        set -o pipefail
        echo "ERROR: fallo al aceptar licencias de Android SDK" >&2
        return 1
    fi
    set -o pipefail

    echo "Instalando platform-tools, platforms;android-34, build-tools;34.0.0..."
    if ! "$sdkmanager" "platform-tools" "platforms;android-34" "build-tools;34.0.0"; then
        echo "ERROR: fallo al instalar paquetes de Android SDK" >&2
        return 1
    fi

    # 5. Genera archivo de entorno
    local env_file="$sdk_dir/env.sh"
    cat > "$env_file" <<EOF
export JAVA_HOME="$JAVA_HOME"
export ANDROID_HOME="$sdk_dir"
export ANDROID_SDK_ROOT="$sdk_dir"
export PATH="\$JAVA_HOME/bin:$sdk_dir/cmdline-tools/latest/bin:$sdk_dir/platform-tools:\$PATH"
EOF

    # 6. Resumen final
    echo ""
    echo "Android SDK instalado en: $sdk_dir"
    echo "JDK 17: $JAVA_HOME"
    echo "Para activar: source $sdk_dir/env.sh"
}

install_android_sdk
