#!/usr/bin/env bash

# This program tries to asign exclusive use of CPU Threads to FREECAD
# to allow the program to runs smootly

# This program needs to use 'sudo or doas' for certan tasks

# JuanMa <numblinux@gmail.com>
# https://linuxnauta.com
# 2025
set -m

VERSION='0.1'
PROGRAM='FreeCAD' # this is the name in Void Linux
CORES=(6 11)


    #If we run the script with unset as parameter we reset all and exit
    if [ "$1" == "unset" ]; then
        sudo cset shield --reset
        cset shield -s -v
        exit
    fi

    #Run FreeCAD
    nohup FreeCAD &

    sleep 2000 &

    pid=$(pgrep -f "$PROGRAM")

    #Is running ?
    if [ -z "${pid}" ]; then
        echo "${PROGRAM} is not running ... so ... exit"
        exit
    else
        echo "The PID of $1 is: $pid"
    fi


    echo "trying to set exclusive use of cores  ${CORES[@]}"

    echo -e "\n"

    cset shield -s -v


    for value in ${CORES[@]}
        do
            CORESTXT=${CORESTXT}"${value},"
        done

    # remove the last ","
    CORESTXT=${CORESTXT:0:-1}

    echo CORESTXT

    sudo cset shield --cpu ${CORESTXT} --kthread
    sudo cset shield --shield --pid ${pid}

    cset shield -s -v


    echo "-----------------------------------------------------------"
    echo " DONT FORGET to RUN  'sudo cset shield --reset' to clear all"
    echo "-----------------------------------------------------------"
    echo " or run the script again with unset as parameter 'sudo freecad-cset unset"
    echo "-----------------------------------------------------------"

    exit
