#!/bin/bash -eu
# SPDX-FileCopyrightText: 2025 Uwe Fechner
# SPDX-License-Identifier: MIT

update=false
julia_version=""

# Parse command line arguments
while [[ $# -gt 0 ]]; do
    case $1 in
        --update)
            update=true
            shift
            ;;
        --version)
            if [[ $# -lt 2 ]]; then
                echo "Error: --version requires a version argument"
                exit 1
            fi
            julia_version="$2"
            shift 2
            ;;
        *)
            echo "Invalid parameter! Use:"
            echo "./create_sys_image"
            echo "or"
            echo "./create_sys_image --update"
            echo "or"
            echo "./create_sys_image --version 1.x"
            exit 1
            ;;
    esac
done

if [[ -n "$julia_version" ]]; then
    JULIA_CMD="julia +$julia_version"
else
    JULIA_CMD="julia"
fi

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

# disable pre-compilation
cp LocalPreferences.toml.default LocalPreferences.toml

export JULIA_PKG_SERVER_REGISTRY_PREFERENCE="eager"

if ! command -v juliaup &> /dev/null; then
    echo "Please install the Julia installer 'juliaup'!"
    echo "See: https://github.com/JuliaLang/juliaup"
    exit 1
fi

# if julia is not installed, install Julia 1.11
if ! command -v julia &> /dev/null; then
    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

totalmem=$(grep MemTotal /proc/meminfo | awk '{printf "%i", $2 / 1024}')
if [[ $totalmem -lt 27000 ]]; then
    echo "Warning: Less than 27GB of memory detected. Using only one thread for sysimage compilation."
    export JULIA_IMAGE_THREADS=1
fi

julia_version=$($JULIA_CMD --version | awk '{print($3)}')
julia_major=${julia_version:0:3}
if [[ $julia_major == "1.1" ]]; then
    julia_major=${julia_version:0:4} 
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_CMD --startup-file=no -e "using Pkg; Pkg.add(\"TestEnv\")"

if [[ $julia_major == "1.10" ]]; then
    rm -f data/model_1.10_*.bin.default
    rm -f data/model_1.10_*.bin
else
    rm -f data/model_1.11_*.bin.default
    rm -f data/model_1.11_*.bin
fi

if [[ $update == true ]]; then
    echo "Updating packages..."
    export JULIA_PKG_SERVER_REGISTRY_PREFERENCE="eager"
    if test -f "Manifest.toml"; then
        mv Manifest.toml Manifest.toml.bak
    fi
    if [[ $julia_major == "1.10" ]]; then
        if test -f "Manifest-v1.10.toml"; then
            mv Manifest-v1.10.toml Manifest-v1.10.toml.bak
        fi
    else
        if test -f "Manifest-v1.11.toml"; then
            mv Manifest-v1.11.toml Manifest-v1.11.toml.bak
        fi
    fi
    $JULIA_CMD --startup-file=no --pkgimages=no --project -e "using TestEnv; TestEnv.activate(); using Pkg; Pkg.add(\"PyCall\"); Pkg.build(\"PyCall\")"
    if [[ $PYTHON == "" ]]; then
        $JULIA_CMD --startup-file=no --pkgimages=no --project -e "using TestEnv; TestEnv.activate(); using Pkg; Pkg.add(\"Conda\"); using Conda; Conda.add(\"matplotlib\"); using ControlPlots"
    fi
    $JULIA_CMD --startup-file=no --pkgimages=no --project -e "using Pkg; Pkg.update()"
    if [[ $julia_major == "1.10" ]]; then
        mv Manifest.toml Manifest-v1.10.toml
    else
        mv Manifest.toml Manifest-v1.11.toml
    fi
else
    if [[ $julia_major == "1.10" ]]; then
        cp Manifest-v1.10.toml.default Manifest-v1.10.toml
        echo "Using Manifest-v1.10.toml.default ..."        
    else
        cp Manifest-v1.11.toml.default Manifest-v1.11.toml
        echo "Using Manifest-v1.11.toml.default ..."
    fi
fi
if [[ $update == true ]]; then
    $JULIA_CMD --startup-file=no --pkgimages=no --project -e "include(\"./test/create_sys_image.jl\");"
else
    $JULIA_CMD --startup-file=no --pkgimages=no --project -e "using Pkg; Pkg.instantiate();"
    $JULIA_CMD --startup-file=no --pkgimages=no --project -e "using TestEnv; TestEnv.activate(); include(\"./test/create_sys_image.jl\");"
fi

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_CMD --startup-file=no  --project -e "using Pkg; Pkg.precompile()"
if [ -d src ]; then
    cd src
    touch *.jl # make sure all modules get recompiled in the next step
    cd ..
fi

# enable pre-compilation
rm LocalPreferences.toml
echo "Precompiling package KiteModels..."
$JULIA_CMD --startup-file=no --project -J $SOFILE -e "using KiteModels, KitePodModels, KiteUtils"
echo "Precompiling package ControlPlots and KiteModelsControlPlotsExt ..."
if [[ $branch != "" ]]; then
    $JULIA_CMD --startup-file=no --project -J $SOFILE -e "using TestEnv; TestEnv.activate(); using ControlPlots, VortexStepMethod, KiteModels"
else
    $JULIA_CMD --startup-file=no --project -J $SOFILE -e "using ControlPlots, VortexStepMethod, KiteModels"
fi

