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

project_root="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)"
tools_directory="$project_root/Linux/.tools"
jdk_home="$tools_directory/jdk-25"
archive="$tools_directory/microsoft-jdk-25-linux-x64.tar.gz"
checksum_file="$archive.sha256sum.txt"
jdk_url="https://aka.ms/download-jdk/microsoft-jdk-25-linux-x64.tar.gz"
checksum_url="$jdk_url.sha256sum.txt"

if [[ -x "$jdk_home/bin/jpackage" ]] && "$jdk_home/bin/java" -version 2>&1 | grep -q '25\.'; then
    echo "Projekt-JDK geprüft: $jdk_home"
    printf '%s\n' "$jdk_home"
    exit 0
fi

mkdir -p "$tools_directory"
if [[ ! -f "$archive" ]]; then
    echo "Lade Microsoft OpenJDK 25 für Linux x64"
    curl --fail --location --output "$archive" "$jdk_url"
fi
curl --fail --location --output "$checksum_file" "$checksum_url"
expected_hash="$(cut -d ' ' -f 1 "$checksum_file")"
echo "$expected_hash  $archive" | sha256sum --check --status || {
    echo "Die SHA-256-Prüfung des Microsoft-JDK ist fehlgeschlagen." >&2
    exit 1
}

temporary_directory="$(mktemp -d "$tools_directory/jdk-extract.XXXXXX")"
trap 'rm -rf -- "$temporary_directory"' EXIT
tar -xzf "$archive" -C "$temporary_directory"
extracted_directory="$(find "$temporary_directory" -mindepth 1 -maxdepth 1 -type d -print -quit)"
if [[ -z "$extracted_directory" || ! -x "$extracted_directory/bin/jpackage" ]]; then
    echo "Das heruntergeladene Archiv enthält kein vollständiges JDK." >&2
    exit 1
fi
if [[ -e "$jdk_home" ]]; then
    echo "Das unvollständige Zielverzeichnis muss manuell entfernt werden: $jdk_home" >&2
    exit 1
fi
mv -- "$extracted_directory" "$jdk_home"

echo "Projekt-JDK installiert: $jdk_home"
printf '%s\n' "$jdk_home"
