#!/bin/sh

# LOG_FILE=/var/log/xiva-audio-conf-$(date +%Y-%m-%d_%H-%M).log
# exec > >(tee -a ${LOG_FILE}) 2>&1

#Aumentar a frequência de interrupção RTC
echo 2048 > /sys/class/rtc/rtc0/max_user_freq
echo 2048 > /proc/sys/dev/hpet/max-user-freq

#configurar o swapness para 10
sysctl vm.swappiness=10
sysctl vm.vfs_cache_pressure=100

#verificar se precisa dar update no grub
grubupdate=0
#se o processador for intel and o pstate estiver ativo
cpuVendor=$(LANG=c cat /proc/cpuinfo | grep vendor | awk '{print $3}' | head -n1)
if [ -n "$(echo $cpuVendor | grep -i intel)" ];then
	intelPstate=$(grep -o '[^[:space:]]*intel_pstate[^[:space:]]*' /etc/default/grub | cut -d "=" -f2 | sed 's/\"//')
	#se tiver 2 entradas com intel_pstate, remover ambas
	if [ "$(echo $intelPstate | wc -w)" -gt "1" ];then
		intelPstate=$(grep -o '[^[:space:]]*intel_pstate[^[:space:]]*' /etc/default/grub | sed 's/\"//')
		for i in ${intelPstate[@]}; do
			sed -i "s/ $i//" /etc/default/grub
		done
		intelPstate=
	fi
	#se não tiver nenhum intel_pstate
	if [ -z "$intelPstate" ]; then
		sed -i '/GRUB_CMDLINE_LINUX_DEFAULT/s/\"/ intel_pstate=disable"/2' /etc/default/grub
		# sed -i '/GRUB_CMDLINE_LINUX_DEFAULT/s/\"/ intel_pstate=passive"/2' /etc/default/grub
		grubupdate=$[$grubupdate+1]
	#se ja tiver mas for diferente de disble
	# elif [ "$intelPstate" != "disable" ]; then
	elif [ "$intelPstate" != "passive" ]; then
		sed -i "s/intel_pstate=$intelPstate/intel_pstate=disable/" /etc/default/grub
		# sed -i "s/intel_pstate=$intelPstate/intel_pstate=passive/" /etc/default/grub
		grubupdate=$[$grubupdate+1]
	fi
fi
#se o processador for AMD e o pstate não estiver ativo
if [ -n "$(echo $cpuVendor | grep -i amd)" ];then
	amdPstate=$(grep -o '[^[:space:]]*amd_pstate[^[:space:]]*' /etc/default/grub | cut -d "=" -f2 | sed 's/\"//')
	#se tiver 2 entradas com amd_pstate, remover ambas
	if [ "$(echo $amdPstate | wc -w)" -gt "1" ];then
		amdPstate=$(grep -o '[^[:space:]]*amd_pstate[^[:space:]]*' /etc/default/grub | sed 's/\"//')
		for i in ${amdPstate[@]}; do
			sed -i "s/ $i//" /etc/default/grub
		done
		amdPstate=
	fi
	#se não tiver nenhum amd_pstate
	if [ -z "$amdPstate" ]; then
		sed -i '/GRUB_CMDLINE_LINUX_DEFAULT/s/\"/ amd_pstate=passive"/2' /etc/default/grub
		grubupdate=$[$grubupdate+1]
	#se ja tiver mas for diferente de ativado
	elif [ "$amdPstate" != "passive" ]; then
		sed -i "s/amd_pstate=$amdPstate/amd_pstate=passive/" /etc/default/grub
		grubupdate=$[$grubupdate+1]
	fi
fi
##desativar o mitigations
mitigations=$(cat /etc/default/grub | grep mitigations=off)
#se o mitigations não estiver em off
if [ -z "$mitigations" ]; then
	sed -i '/GRUB_CMDLINE_LINUX_DEFAULT/s/\"/ mitigations=off"/2' /etc/default/grub
	#update-grub
	grubupdate=$[$grubupdate+1]
fi
#se o clearcpuid não estiver incluir
clearcpuid=$(cat /etc/default/grub | grep clearcpuid=514)
if [ -z "$clearcpuid" ]; then
	sed -i '/GRUB_CMDLINE_LINUX_DEFAULT/s/\"/ clearcpuid=514"/2' /etc/default/grub
	#update-grub
	grubupdate=$[$grubupdate+1]
fi
#se o nowatchdog não estiver incluir
nowatchdog=$(cat /etc/default/grub | grep nowatchdog)
if [ -z "$nowatchdog" ]; then
	sed -i '/GRUB_CMDLINE_LINUX_DEFAULT/s/\"/ nowatchdog"/2' /etc/default/grub
	#update-grub
	grubupdate=$[$grubupdate+1]
fi
#se o nosoftlockup não estiver incluir
nosoftlockup=$(cat /etc/default/grub | grep nosoftlockup)
if [ -z "$nosoftlockup" ]; then
	sed -i '/GRUB_CMDLINE_LINUX_DEFAULT/s/\"/ nosoftlockup"/2' /etc/default/grub
	#update-grub
	grubupdate=$[$grubupdate+1]
fi
#se o audit não estiver incluir
audit=$(cat /etc/default/grub | grep audit)
if [ -z "$audit" ]; then
	sed -i '/GRUB_CMDLINE_LINUX_DEFAULT/s/\"/ audit=0"/2' /etc/default/grub
	#update-grub
	grubupdate=$[$grubupdate+1]
fi
#se o skewtick não estiver incluir
skewtick=$(cat /etc/default/grub | grep skew_tick=1)
if [ -z "$skewtick" ]; then
	sed -i '/GRUB_CMDLINE_LINUX_DEFAULT/s/\"/ skew_tick=1"/2' /etc/default/grub
	#update-grub
	grubupdate=$[$grubupdate+1]
fi
#se o threadirqs não estiver incluir
threadirqs=$(cat /etc/default/grub | grep threadirqs)
if [ -z "$threadirqs" ]; then
	sed -i '/GRUB_CMDLINE_LINUX_DEFAULT/s/\"/ threadirqs"/2' /etc/default/grub
	#update-grub
	grubupdate=$[$grubupdate+1]
fi
#executar update do grub se for necessario
if [ "$grubupdate" -gt "0" ]; then 
    update-grub
fi

#libera memoria pra audio
if [ -z "$(grep 'rtprio     95' /etc/security/limits.conf)" ]; then
    echo "@audio   -  rtprio     95" | tee -a /etc/security/limits.conf
fi
if [ -z "$(grep 'memlock    unlimited' /etc/security/limits.conf)" ]; then 
    echo "@audio   -  memlock    unlimited" | tee -a /etc/security/limits.conf
fi
if [ -e /usr/share/pipewire/jack.conf -a -n "$(grep rt.prio /usr/share/pipewire/jack.conf | grep \#)" ]; then
    sed -i '/rt.prio/s/#//' /usr/share/pipewire/jack.conf
fi
if [ -e /usr/share/pipewire/jack.conf -a -z "$(grep rt.prio /usr/share/pipewire/jack.conf | grep 95)" ]; then
    sed -i '/rt.prio/s/rt.prio.*/rt.prio      = 95/' /usr/share/pipewire/jack.conf
fi
    
#PAM-enabled login
if [ -z "$(grep pam_limits.so /etc/pam.d/crond)" ]; then
    echo "session   required    pam_limits.so" | tee -a /etc/pam.d/crond
fi
if [ -z "$(grep pam_limits.so /etc/pam.d/login)" ]; then
    echo "session   required    pam_limits.so" | tee -a /etc/pam.d/login
fi
if [ -z "$(grep pam_limits.so /etc/pam.d/polkit-1)" ]; then
    echo "session   required    pam_limits.so" | tee -a /etc/pam.d/polkit-1
fi
if [ -z "$(grep pam_limits.so /etc/pam.d/system-auth)" ]; then
    echo "session   required    pam_limits.so" | tee -a /etc/pam.d/system-auth
fi
if [ -z "$(grep pam_limits.so /etc/pam.d/system-services)" ]; then
    echo "session   required    pam_limits.so" | tee -a /etc/pam.d/system-services
fi

##adicionar usuario aos grupos realtime, video e audio
#descobrir o nome do(s) usuario(s)
users=$(ls /home)
for who in $users; do 
    #adicinar usuario ao grupo realtime e video
    if [ -z "$(getent group | grep realtime | grep $who)" ];then
        usermod -a -G realtime $who
    fi
    if [ -z "$(getent group | grep video | grep $who)" ];then
        usermod -a -G video $who
    fi
    if [ -z "$(getent group | grep audio | grep $who)" ];then
        usermod -a -G audio $who
    fi
done

#baixar a latencia das placas de audio PCI internas
for i in $(lspci | grep -i audio | awk '{print $1}'); do 
    setpci -v -s $i latency_timer=ff
done

udevadm control --reload-rules
udevadm trigger
