#!/bin/bash -eu

if [[ $(basename $(pwd)) == "bin" ]]; then
    cd ..
fi

mkdir -p output

export MPLBACKEND=agg
export JULIA_PKG_SERVER_REGISTRY_PREFERENCE="eager"

if ! command -v juliaup &> /dev/null; then
    echo "Juliaup not found. Please run: ./install"
    exit 1
fi

# if julia is not installed, install Julia 1.11
if ! command -v julia &> /dev/null; then
    echo "Julia not found. Please run: ./install"
    exit 1
fi

if [[ "$(uname -s)" == "Linux" ]]; then
    export FONTCONFIG_FILE=/etc/fonts/fonts.conf
    # Preload Julia-bundled libraries to avoid version conflicts with older system libs.
    # On Ubuntu 22.04: OpenSSL 3.0.2 (artifacts need 3.3+), fontconfig 2.13 (missing
    # FcConfigSetDefaultSubstitute added in 2.15). The dynamic linker reuses already-loaded
    # system libs instead of the bundled ones, so we force the bundled versions in first.
    _PRELOADS=()
    _BUNDLED=$(find ~/.julia/artifacts -maxdepth 3 -name "libcrypto.so.3" -path "*/lib/*" 2>/dev/null | head -1); [[ -n "$_BUNDLED" ]] && _PRELOADS+=("$_BUNDLED")
    # Preload libintl and libiconv before libglib (libglib depends on both; system versions may be missing).
    _BUNDLED=$(find ~/.julia/artifacts -maxdepth 3 -name "libintl.so.8" -path "*/lib/*" 2>/dev/null | head -1); [[ -n "$_BUNDLED" ]] && _PRELOADS+=("$_BUNDLED")
    _BUNDLED=$(find ~/.julia/artifacts -maxdepth 3 -name "libiconv.so.2" -path "*/lib/*" 2>/dev/null | head -1); [[ -n "$_BUNDLED" ]] && _PRELOADS+=("$_BUNDLED")
    # Pick the glib that exports g_string_copy (needed by libgobject >= 2.75).
    # Must be loaded before libgobject; multiple versions may coexist.
    _BUNDLED=""
    for _gl in $(find ~/.julia/artifacts -maxdepth 3 -name "libglib-2.0.so.0" -path "*/lib/*" 2>/dev/null); do
        if nm -D "$_gl" 2>/dev/null | grep -q g_string_copy; then
            _BUNDLED="$_gl"
            break
        fi
    done
    [[ -n "$_BUNDLED" ]] && _PRELOADS+=("$_BUNDLED")
    # Pick the fontconfig that exports FcConfigSetDefaultSubstitute (needed by Pango >= 1.57).
    # Multiple artifact versions may coexist; `find | head -1` can return the wrong one.
    _BUNDLED=""
    for _fc in $(find ~/.julia/artifacts -maxdepth 3 -name "libfontconfig.so.1" -path "*/lib/*" 2>/dev/null); do
        if nm -D "$_fc" 2>/dev/null | grep -q FcConfigSetDefaultSubstitute; then
            _BUNDLED="$_fc"
            break
        fi
    done
    [[ -n "$_BUNDLED" ]] && _PRELOADS+=("$_BUNDLED")
    if [[ ${#_PRELOADS[@]} -gt 0 ]]; then
        export LD_PRELOAD=$(IFS=:; echo "${_PRELOADS[*]}")
    fi
    unset _PRELOADS _BUNDLED
fi

julia_version=$(julia --version | awk '{print($3)}')
julia_major=${julia_version:0:3}
if [[ $julia_major == "1.1" ]]; then
    julia_major=${julia_version:0:4} 
fi

# if the current julia version is older than 1.10, exit
if [[ $julia_major == "1.11" ]] || [[ $julia_major == "1.12" ]]; then
    echo "Supported Julia version found!"
else
    echo "The current Julia version is not supported, installing Julia 1.11!"
    juliaup add 1.11
    juliaup default 1.11
fi

PYTHON_PATH=$(which python3)
if [ -x "$PYTHON_PATH" ]; then
    echo "Python is found at $PYTHON_PATH"
    if $PYTHON_PATH -c "import matplotlib" &> /dev/null; then
        echo "Matplotlib found. Using existing installation."
        export PYTHON=$PYTHON_PATH
    else
        echo "Matplotlib is not found."
        read -p "Do you want to install matplotlib with Conda? (y/n): " choice
        case "$choice" in 
          y|Y ) 
            export PYTHON=""
            ;;
          n|N ) 
            echo "Exiting without installing matplotlib."
            exit 1
            ;;
          * ) 
            echo "Invalid choice. Exiting."
            exit 1
            ;;
        esac
    fi
else
    echo "Python is not found."
    exit 1
fi

# create a logfile for the sysimage creation process
./bin/batch_pilot hydra20_600

# Check memory and limit threads if needed
if [[ "$OSTYPE" == "msys" || "$OSTYPE" == "win32" ]]; then
    # Windows: use wmic or PowerShell
    echo "Checking system memory on Windows..."
    totalmem=$(powershell.exe -Command "(Get-CimInstance Win32_ComputerSystem).TotalPhysicalMemory / 1MB" 2>/dev/null | awk '{printf "%i", $1}')
    if [[ -z "$totalmem" || $totalmem -lt 27000 ]]; then
        echo "Warning: Less than 27GB of memory detected on Windows. Using only one thread for sysimage compilation."
        export JULIA_IMAGE_THREADS=1
    fi
elif [[ "$OSTYPE" == darwin* ]]; then
    # macOS: use sysctl
    echo "Checking system memory on macOS..."
    totalmem=$(sysctl -n hw.memsize 2>/dev/null | awk '{printf "%i", $1 / 1000000}')
    if [[ -z "$totalmem" || $totalmem -lt 27000 ]]; then
        echo "Warning: Less than 27GB of memory detected on macOS. Using only one thread for sysimage compilation."
        export JULIA_IMAGE_THREADS=1
    fi
else
    # Linux: use /proc/meminfo
    totalmem=$(grep MemTotal /proc/meminfo | awk '{printf "%i", $2 / 1024}')
    if [[ $totalmem -lt 26674 ]]; then
        echo "Warning: Less than 27GB of memory detected. Using only one thread for sysimage compilation."
        export JULIA_IMAGE_THREADS=1
    fi
fi

if [ -d .git ] || git rev-parse --git-dir > /dev/null 2>&1 ; then
    branch=$(git rev-parse --abbrev-ref HEAD | sed 's/\//-/g')
else
    branch=""
fi
if test -f "kps-image-${julia_major}-${branch}.so"; then
    mv bin/kps-image-${julia_major}-${branch}.so kps-image-${julia_major}-${branch}.so.bak
fi

julia --startup-file=no --project -e "using Pkg; Pkg.instantiate();"
julia --startup-file=no --project=test -e "include(\"./test/create_sys_image.jl\")"

if [[ $branch != "" ]]; then
    SOFILE="bin/kps-image-${julia_major}-${branch}.so"
else
    SOFILE="bin/kps-image-${julia_major}.so"
fi
if test -f $SOFILE; then
    mv $SOFILE $SOFILE.bak
fi
mv kps-image_tmp.so $SOFILE
julia --startup-file=no  --project -e "using Pkg; Pkg.precompile(); Pkg.resolve()"
julia --project -J bin/kps-image-${julia_major}-${branch}.so -e "using KiteUtils, KiteControllers"
julia --project=test -J bin/kps-image-${julia_major}-${branch}.so -e "using ControlPlots, NativeFileDialog"
julia --project -J bin/kps-image-${julia_major}-${branch}.so -e "using Pkg; Pkg.instantiate()"
julia --project=docs -J bin/kps-image-${julia_major}-${branch}.so -e "using LiveServer, Documenter, Pkg; Pkg.instantiate()"
julia --project=examples -J bin/kps-image-${julia_major}-${branch}.so -e "using NOMAD, Pkg; Pkg.instantiate(); Pkg.precompile()"