#!/bin/sh
# Rune Haven launcher for Linux and Mac. It replaces itself with the copy
# on the site, then installs Java 11 if needed and starts the published jar.
set -eu
set -f
umask 077
# Bound both connection and transfer stalls; identify this client to the Java provider.
fetch() { curl --connect-timeout 15 --max-time 900 --speed-time 30 --speed-limit 128 --retry 2 --retry-delay 1 -A "RuneHavenLauncher/1.1" -fL "$@"; }
ORIGIN="https://rune-havenps.com"

if [ "${RH_LAUNCHER_FRESH:-}" != "1" ]; then
    tmp=$(mktemp)
    if fetch "$ORIGIN/downloads/launcher.sh" -o "$tmp"; then
        RH_LAUNCHER_FRESH=1
        export RH_LAUNCHER_FRESH
        result=0
        /bin/sh "$tmp" "$@" || result=$?
        rm -f "$tmp"
        exit "$result"
    fi
    rm -f "$tmp"
fi

if ! command -v curl >/dev/null 2>&1; then
    echo "curl is required." >&2
    exit 1
fi

case "$(uname -s)" in
    Linux) osname=linux; install="${XDG_DATA_HOME:-$HOME/.local/share}/RuneHaven" ;;
    Darwin) osname=mac; install="$HOME/Library/Application Support/RuneHaven" ;;
    *) echo "This launcher supports Linux and Mac. On Windows, run RuneHavenSetup.exe." >&2; exit 1 ;;
esac

mach=$(uname -m)
case "$mach" in
    x86_64|amd64) arch=x64 ;;
    aarch64|arm64) arch=aarch64 ;;
    i686|i386) echo "Rune Haven requires a 64-bit operating system." >&2; exit 1 ;;
    *) echo "Unsupported processor: $mach" >&2; exit 1 ;;
esac

if [ "$osname" = linux ] && [ "$arch" != x64 ]; then
    echo "This client currently includes native graphics libraries for x86-64 Linux only." >&2
    exit 1
fi
mkdir -p "$install"


file_sha() {
    raw=""
    if command -v sha256sum >/dev/null 2>&1; then
        raw=$(sha256sum "$1" | awk '{print $1}')
    elif command -v shasum >/dev/null 2>&1; then
        raw=$(shasum -a 256 "$1" | awk '{print $1}')
    else
        echo "Need sha256sum or shasum to check the download." >&2
        exit 1
    fi
    printf '%s' "$raw" | tr 'A-F' 'a-f'
}

java_ok() {
    [ -x "$1" ] || return 1
    probe_file=$(mktemp "$install/java-probe.XXXXXX")
    "$1" -XshowSettings:properties -version >"$probe_file" 2>&1 &
    probe_pid=$!
    probe_ticks=0
    while kill -0 "$probe_pid" 2>/dev/null && [ "$probe_ticks" -lt 10 ]; do
        sleep 1
        probe_ticks=$((probe_ticks + 1))
    done
    if kill -0 "$probe_pid" 2>/dev/null; then kill "$probe_pid" 2>/dev/null || true; fi
    probe_status=0
    wait "$probe_pid" || probe_status=$?
    result=1
    if [ "$probe_status" = 0 ] &&
       grep -Eq 'java.specification.version = 11[[:space:]]*$' "$probe_file" &&
       grep -Eq 'sun.arch.data.model = 64[[:space:]]*$' "$probe_file"; then
        case "$arch" in
            x64) grep -Eq 'os.arch = (amd64|x86_64)[[:space:]]*$' "$probe_file" && result=0 ;;
            aarch64) grep -Eq 'os.arch = aarch64[[:space:]]*$' "$probe_file" && result=0 ;;
        esac
    fi
    rm -f "$probe_file"
    return "$result"
}

echo "Checking for a new client..."
meta=$(mktemp "$install/manifest.XXXXXX")
trap 'rm -f "$meta"' EXIT
trap 'exit 130' HUP INT TERM
fetch "$ORIGIN/downloads/launcher.txt" -o "$meta"
if ! grep -q '^jar=' "$meta"; then
    echo "The site did not return a launcher manifest." >&2
    exit 1
fi

version=""
main="com.rhaven.Client"
jar=""
sha=""
jvm=""
java_version=11
while IFS= read -r line || [ -n "$line" ]; do
    line=$(printf '%s' "$line" | tr -d '\r')
    key=${line%%=*}
    val=${line#*=}
    case "$key" in
        version) version=$val ;;
        java) java_version=$val ;;
        main) main=$val ;;
        jar) jar=$val ;;
        sha256) sha=$val ;;
        jvm) case "$val" in -Xms*) ;; *) jvm="$jvm $val" ;; esac ;;
    esac
done < "$meta"

if [ -z "$jar" ]; then
    echo "No client has been published yet. Check Discord, then run this again."
    exit 1
fi

case "$jar" in
    RuneHaven-[0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f].jar) ;;
    *) echo "The published jar name is not valid." >&2; exit 1 ;;
esac

case "$main" in
    *[!A-Za-z0-9_.]*) echo "The manifest main class is not valid." >&2; exit 1 ;;
    "") main="com.rhaven.Client" ;;
esac

if [ "$java_version" != 11 ]; then echo "This client requires a newer launcher." >&2; exit 1; fi
if [ "$main" != com.rhaven.Client ]; then echo "Unsupported client entry point." >&2; exit 1; fi
sha=$(printf '%s' "$sha" | tr 'A-F' 'a-f')
if ! printf '%s\n' "$sha" | grep -Eq '^[a-f0-9]{64}$'; then
    echo "The published SHA-256 checksum is invalid." >&2; exit 1
fi
prefix=$(printf '%s' "$sha" | cut -c 1-12)
if [ "$jar" != "RuneHaven-$prefix.jar" ]; then echo "Client name/checksum mismatch." >&2; exit 1; fi
jvm=$(printf '%s' "$jvm" | sed 's/^ *//')
if [ -z "$jvm" ]; then
    jvm="-Xmx2g"
fi

jvm="$jvm -Xms256m"
checked=""
for flag in $jvm; do
    if ! printf '%s\n' "$flag" | grep -Eq '^-[-A-Za-z0-9:.=+,/_]{1,120}$'; then
        echo "A JVM flag is not allowed: $flag" >&2
        exit 1
    fi
    checked="$checked $flag"
done
jvm=$(printf '%s' "$checked" | sed 's/^ *//')

dest="$install/$jar"
need=1
if [ -f "$dest" ] && [ -n "$sha" ]; then
    have=$(file_sha "$dest")
    if [ "$have" = "$sha" ]; then
        need=0
    fi
fi
if [ "$need" -eq 1 ]; then
    echo "Downloading $jar..."
    part=$(mktemp "$install/client.part.XXXXXX")
    if ! fetch "$ORIGIN/downloads/$jar" -o "$part"; then rm -f "$part"; exit 1; fi
    have=$(file_sha "$part")
    if [ -n "$sha" ] && [ "$have" != "$sha" ]; then
        rm -f "$part"
        echo "The download did not match. Try again in a minute." >&2
        exit 1
    fi
    mv -f "$part" "$dest"
else
    echo "The client is already up to date."
fi

find_java() {
    bundled="$install/jre/bin/java"
    if java_ok "$bundled"; then
        printf '%s\n' "$bundled"
        return 0
    fi
    if [ -n "${JAVA_HOME:-}" ] && java_ok "$JAVA_HOME/bin/java"; then
        printf '%s\n' "$JAVA_HOME/bin/java"
        return 0
    fi
    if command -v java >/dev/null 2>&1; then
        sys=$(command -v java)
        if java_ok "$sys"; then
            printf '%s\n' "$sys"
            return 0
        fi
    fi
    return 1
}

install_jre() {
    echo "Installing compatible 64-bit Temurin Java 11..." >&2
    staging=$(mktemp -d "$install/runtime.XXXXXX")
    metadata="$staging/java.json"
    fetch "https://api.adoptium.net/v3/assets/latest/11/hotspot?architecture=${arch}&image_type=jre&os=${osname}&vendor=eclipse" -o "$metadata"
    # The official latest-assets response's first package contains these fields.
    runtime_hash=$(sed -n 's/^[[:space:]]*"checksum": "\([a-f0-9]*\)".*/\1/p' "$metadata" | head -n 1)
    runtime_url=$(sed -n 's/^[[:space:]]*"link": "\(https:[^"]*\)".*/\1/p' "$metadata" | head -n 1)
    if ! printf '%s\n' "$runtime_hash" | grep -Eq '^[a-f0-9]{64}$'; then
        echo "The Java provider returned invalid metadata." >&2; exit 1
    fi
    case "$runtime_url" in
        https://github.com/adoptium/temurin11-binaries/releases/download/*.tar.gz) ;;
        *) echo "Unexpected Java download location." >&2; exit 1 ;;
    esac
    tgz="$staging/runtime.tgz"
    fetch "$runtime_url" -o "$tgz"
    if [ "$(file_sha "$tgz")" != "$runtime_hash" ]; then
        echo "Java checksum mismatch. Existing runtime kept." >&2; exit 1
    fi
    mkdir "$staging/unpack"
    tar -xzf "$tgz" -C "$staging/unpack"
    jbin=$(find "$staging/unpack" -type f -path '*/bin/java' | head -n 1)
    if [ -z "$jbin" ] || ! java_ok "$jbin"; then
        echo "The downloaded Java cannot run on this machine." >&2; exit 1
    fi
    # Launch directly from this verified, unique runtime directory. No live runtime is overwritten.
    JAVA_BIN=$jbin
    printf '%s\n' "$jbin" > "$install/java-path.txt.new.$$"
    mv -f "$install/java-path.txt.new.$$" "$install/java-path.txt"
    rm -f "$tgz" "$metadata"
}

JAVA_BIN=""
if [ -f "$install/java-path.txt" ]; then
    stored_java=$(cat "$install/java-path.txt")
    case "$stored_java" in "$install"/runtime.*/unpack/*/bin/java|"$install"/runtime.*/unpack/*/Contents/Home/bin/java)
        if java_ok "$stored_java"; then JAVA_BIN=$stored_java; fi ;;
    esac
fi
if [ -z "${JAVA_BIN:-}" ] && ! JAVA_BIN=$(find_java); then
    install_jre
fi

echo "Starting Rune Haven $version"
cd "$install"
# Flags were checked above and contain no spaces or shell characters.
# shellcheck disable=SC2086
mkdir -p "$install/logs"
client_log="$install/logs/client-$(date +%Y%m%d-%H%M%S)-$$.log"
echo "Client log: $client_log"
client_result=0
"$JAVA_BIN" $jvm -cp "$dest" "$main" "$@" >"$client_log" 2>&1 || client_result=$?
if [ "$client_result" != 0 ]; then
    echo "Rune Haven closed with error $client_result. Last startup messages:" >&2
    tail -n 30 "$client_log" >&2
    echo "Try again with --safe-mode to disable optional plugins." >&2
fi
exit "$client_result"
