#!/bin/bash -eu
# Copyright (c) 2025 Uwe Fechner
# SPDX-License-Identifier: BSD-3-Clause

# Start script for multithreaded, normal use of FLORIDyn

# If you do not want to use Revise.jl, uncomment the following line
# USE_REVISE=false

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

# export JULIA_DEBUG=Main,FLORIDyn

# Treats unset/empty as true
if [[ "${USE_REVISE:-true}" == "true" ]]; then
    echo "Revise is ON"
    # Install TerminalPager and Timers and Revise and ControlPlots globally, if not yet installed
    julia -e 'using Pkg;
    globaldependencies() = keys(Pkg.project().dependencies)
    if ! ("TerminalPager" in globaldependencies()); Pkg.add("TerminalPager"); end;
    if ! ("Timers" in globaldependencies()); Pkg.add("Timers"); end;
    if ! ("Revise" in globaldependencies()); Pkg.add("Revise"); end;
    if ! ("ControlPlots" in globaldependencies()); Pkg.add("ControlPlots"); end;'
    # Run Julia with 8 threads and load FLORIdyn
    # In addition, define the function menu()
    julia --project -t 11 --gcthreads=4,1 -i -e 'using Revise; using FLORIDyn; function menu(); include("examples/menu.jl"); end'
else
    echo "Revise is OFF"
    # Install TerminalPager and Timers and Revise and ControlPlots globally, if not yet installed
    julia -e 'using Pkg;
    globaldependencies() = keys(Pkg.project().dependencies)
    if ! ("TerminalPager" in globaldependencies()); Pkg.add("TerminalPager"); end;
    if ! ("Timers" in globaldependencies()); Pkg.add("Timers"); end;
    if ! ("ControlPlots" in globaldependencies()); Pkg.add("ControlPlots"); end;'
    # Run Julia with 11 threads and load FLORIdyn
    # In addition, define the function menu()
    if [[ $julia_major == "1.12" ]]; then
        julia --project -t 11,1 -i --gcthreads=4,0 -e 'using FLORIDyn; function menu(); include("examples/menu.jl"); end'
    else
        julia --project -t 11 --gcthreads=4,1 -i -e 'using FLORIDyn; function menu(); include("examples/menu.jl"); end'
    fi
fi

# ON DESKTOP Ryzen 7 7850X
#  38s for 300 iterations with threading=true and parallel=true enabled 4.8x advantage
# 184s for 300 iterations with threading=false and parallel=false

# ON LAPTOP, Ryzen 7840U, performance mode on power
#  53s on laptop multithreaded 4.3x advantage
# 234s on laptop single threaded 
