#!/bin/bash

# die on errors
set -e

COMPILED="@false@"

if [ "$COMPILED" != "true" ] ; then
  echo "You are trying to run the Severed Chains source code. Please see our installation instructions at https://legendofdragoon.org/projects/severed-chains/"
  read -p "Press enter to exit"
  exit 1;
fi

SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
cd "$SCRIPT_DIR"

# Load launch configuration
GPU_PREFERENCE=0
if [[ -f ./launch.conf ]]; then
  source ./launch.conf
fi

# Apply GPU preference
case "$GPU_PREFERENCE" in
  1)
    # High Performance (Dedicated AMD or NVIDIA GPU)
    export DRI_PRIME=1
    export __NV_PRIME_RENDER_OFFLOAD=1
    export __GLX_VENDOR_LIBRARY_NAME=nvidia
    ;;
  2)
    # Integrated Graphics Only
    export __NV_PRIME_RENDER_OFFLOAD=0
    unset __GLX_VENDOR_LIBRARY_NAME

    # Cascade fallback string for Intel and AMD open-source stacks
    export MESA_LOADER_DRIVER_OVERRIDE=iris:crocus
    export MESA_LOADER_DRIVER_OVERRIDE_AMD=radeonsi

    # Universal fallback layout matching standard motherboard PCI architectures
    export DRI_PRIME=pci-0000_00_02_0
    ;;
  0|*)
    # Let the OS Decide
    unset DRI_PRIME
    unset __NV_PRIME_RENDER_OFFLOAD
    unset __GLX_VENDOR_LIBRARY_NAME
    unset MESA_LOADER_DRIVER_OVERRIDE
    unset MESA_LOADER_DRIVER_OVERRIDE_AMD
    ;;
esac

if [[ $(pwd) == *":"* ]]; then
  echo "Java cannot launch with a colon (:) in the path. Please rename the directory or move Severed Chains to a different directory."
  echo "Current directory: $(pwd)"
  read -p "Press enter to exit"
  exit 1;
fi

JAVA=./jdk25/bin/java

if [[ ! -f $JAVA ]]
then
  ./download-java
fi

__GL_THREADED_OPTIMIZATIONS=0 "$JAVA" -Djoml.fastmath -Djoml.sinLookup -Djoml.useMathFma --add-opens java.base/java.util=ALL-UNNAMED --add-exports java.base/jdk.internal.misc=ALL-UNNAMED --enable-native-access=ALL-UNNAMED -cp "lod-game-@version@.jar:@libs@" legend.game.Main -Xmx2G -ea
read -p "Press enter to exit"
