#!/bin/bash

# Copyright Piero Olmeda - AudioLinux  <audiolinux AT fastmail DOT fm>
# https://www.audio-linux.com

# License: custom - All rights reserved

source /etc/rtpriority/rtirqs.conf
source /etc/rtpriority/rtapp.conf
AUDIO_PRIORITY=$(echo -e "$PRIORITY1\n$PRIORITY2\n$PRIORITY3\n$PRIORITY4\n$PRIORITY5" | sed 's/PRIORITY[1-9]//g' | awk 'NF' | sort -n | head -n 1)

#rtpriorityreset "echo $APPLICATIONS | sed 's/ /|/g'"

update_priority () {
                for WORD in $APPLICATIONS
                do
                (pidof $WORD 1>/dev/null && chrt -f -a -p $fifo_app $(pidof $WORD))
                done
} 

update_priority_dec () {
                for WORD in $APPLICATIONS
                do
                    if [[ "$(pidof $WORD)" ]]
                    then                                           
                      chrt -f -a -p $fifo_app $(pidof $WORD)
                      fifo_app=$(( $fifo_app - $PRIORITY_STEP )) 
                    fi
                done
}

case $MODE in

manual)
                fifo_app=$MAX_PRIORITY
                if [[ $MAX_PRIORITY -le $AUDIO_PRIORITY ]]; then
                    update_priority
                else
                    echo "The priority is higher than IRQ priority"
            
                fi
        ;;

auto)           
                fifo_app=$(( $AUDIO_PRIORITY - $PRIORITY_STEP ))
                update_priority
        ;;
        
autodec)
                fifo_app=$(( $AUDIO_PRIORITY - $PRIORITY_STEP ))
                update_priority_dec
        ;;

manualdec)
                fifo_app=$MAX_PRIORITY
                if [[ $MAX_PRIORITY -le $AUDIO_PRIORITY ]]; then
                    update_priority_dec
                else
                    echo "The priority is higher than IRQ priority"
            
                fi
        ;;
        
esac


