#!/bin/bash
# ytgram launcher. ~/.local/bin is prepended so the pipx yt-dlp shim is visible
# even when a desktop session starts Java with a short PATH.

export PATH="$HOME/.local/bin:${PATH:-/usr/bin:/bin}"

java_major() {
    "$1" -version 2>&1 | awk -F '"' '/version/ {print $2}' | awk -F '.' '{print $1}'
}

java_is_new_enough() {
    local major
    major=$(java_major "$1")
    [ -n "$major" ] && [ "$major" -ge 21 ] 2>/dev/null
}

select_java() {
    local candidate
    local -a homes
    if [ -n "${JAVA_HOME:-}" ] && [ -x "$JAVA_HOME/bin/java" ] && java_is_new_enough "$JAVA_HOME/bin/java"; then
        printf '%s\n' "$JAVA_HOME/bin/java"
        return 0
    fi
    if command -v java >/dev/null 2>&1 && java_is_new_enough "$(command -v java)"; then
        command -v java
        return 0
    fi
    shopt -s nullglob
    homes=(/usr/lib/jvm/java-*-openjdk-*/bin/java)
    shopt -u nullglob
    for candidate in "${homes[@]}"; do
        if [ -x "$candidate" ] && java_is_new_enough "$candidate"; then
            printf '%s\n' "$candidate"
            return 0
        fi
    done
    return 1
}

install_java() {
    echo "Java 21 or newer is required to run ytgram." >&2
    if ! command -v pkexec >/dev/null 2>&1 || [ ! -x /usr/bin/apt-get ]; then
        echo "There is no password dialog available to install it." >&2
        echo "Install it yourself, then try again: sudo apt-get install -y default-jre" >&2
        exit 1
    fi
    echo "A password dialog will ask to install the default-jre package." >&2
    if ! pkexec /usr/bin/apt-get install -y default-jre; then
        status=$?
        if [ "$status" -eq 126 ] || [ "$status" -eq 127 ]; then
            echo "Java installation cancelled." >&2
        else
            echo "Could not install default-jre (pkexec status $status)." >&2
        fi
        exit 1
    fi
}

if ! JAVA=$(select_java); then
    install_java
    hash -r
    if ! JAVA=$(select_java); then
        echo "default-jre was installed but Java 21 or newer is still not available." >&2
        exit 1
    fi
fi

ROOT="$(cd "$(dirname "$0")" && pwd)"
if [ -f "$ROOT/ytgram.jar" ]; then
    JAR="$ROOT/ytgram.jar"
elif [ -f "$HOME/.local/share/ytgram/ytgram.jar" ]; then
    JAR="$HOME/.local/share/ytgram/ytgram.jar"
elif [ -f /usr/share/ytgram/ytgram.jar ]; then
    JAR=/usr/share/ytgram/ytgram.jar
else
    echo "Error: ytgram.jar was not found." >&2
    exit 1
fi

exec "$JAVA" \
    -Dawt.useSystemAAFontSettings=on \
    -Dswing.aatext=true \
    -jar "$JAR" "$@"
