#!/bin/bash -eu
update=false
if [[ $# -gt 0 ]]; then
    if [[ $1 != "--update" ]]; then
        echo "Invalid parameter! Use:"
        echo "./create_sys_image"
        echo "or"
        echo "./create_sys_image --update"
        exit 1
    else
        update=true
    fi
fi

if [[ $(basename $(pwd)) == "bin" ]]; then
    cd ..
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 [ -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 -e "using Pkg; Pkg.add(\"TestEnv\")"

if [[ $update == true ]]; then
    echo "Updating packages..."
    if test -f "Manifest.toml"; then
        mv Manifest.toml Manifest.toml.bak
    fi
    julia  --pkgimages=no --project -e "include(\"./test/update_packages.jl\");"
else
    if [[ $julia_major == "1.9" ]]; then
        cp Manifest-1.9.toml.default Manifest.toml
        echo "Using Manifest-1.9.toml.default ..."        
    else
        cp Manifest-1.10.toml.default Manifest.toml
        echo "Using Manifest-1.10.toml.default ..."
    fi
fi
julia --pkgimages=no --project -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  --project -e "using Pkg; Pkg.precompile(); Pkg.resolve()"
if [ -d src ]; then
    cd src
    touch *.jl # make sure all modules get recompiled in the next step
    cd ..
fi
echo "Precompiling package KiteModels..."
julia --project -J $SOFILE -e "using KiteModels, KitePodModels, KiteUtils"
echo "Precompiling package ControlPlots..."
if [[ $branch != "" ]]; then
    julia --project -J $SOFILE -e "using TestEnv; TestEnv.activate(); using ControlPlots"
else
    julia --project -J $SOFILE -e "using ControlPlots"
fi
