#!/bin/bash
inifilename="/boot/grub/grubParams.ini"
bootconf="/boot/grub/grub.cfg"
cpuarch=$(uname -p)

noini=0
nobootconf=0

inifilename=$1
bootconf=$2

if [ -z $inifilename ]; then
	#echo "no inifilename, use default..."
	inifilename="/boot/grub/grubParamsEFI.ini"
	noini=1
fi

if [ -z $bootconf ]; then
	#echo "no bootconf, use default..."
	bootconf="/boot/efi/boot/grub/grub.cfg"
	nobootconf=1
fi

if [[ $cpuarch = aarch64 && $noini = 1 && $nobootconf = 1 ]]; then
	#echo cpuarch=$cpuarch
	inifilename="/boot/grub/grubParamsEFI.ini"
	bootconf="/boot/efi/boot/grub/grub.cfg"
fi

if [[ $cpuarch = loongarch64 && $noini = 1 && $nobootconf = 1 ]]; then
	#echo cpuarch=$cpuarch
	inifilename="/boot/grub/grubParamsEFI.ini"
	bootconf="/boot/efi/boot/EFI/grub.cfg"
fi

#echo "inifilename:$inifilename"
#echo "bootconf:$bootconf"

startflg=0

if [ -f $inifilename ] && [ -v control_center_support_grub_parameter ]; then
	while read -r line; do
		if [[ "$line" = "[LatestSettings]" ]]; then
			startflg=1
		elif [[ $startflg -eq 1 ]] && [[ $line = [* ]]; then
			#                echo "end:"$line
			startflg=2
		elif [[ $startflg = 1 ]] && [[ $line != "" ]]; then
			#                echo "search:"$line
			id=$(echo $line | awk -F '="' '{print $1}')
			params=$(echo $line | awk -F '="' '{print $2}' | sed 's/\\t/\t/g' | sed 's/"//g')
			#                echo $id
			#                echo $params
			id_no=$(grep -nr $id $bootconf | awk -F ':' '{print $1}')
			#echo "id_no, id:" $id_no $id
			dno=$(expr $((id_no)) + 4)

			# get dno
			cfglinenbr=0
			should_start=0
			start_line=0
			while read -r cfgline; do
				if [[ $id_no == "" ]]; then
					id_no=0
					break
				fi
				cfglinenbr=$(($cfglinenbr + 1))
				if [ $cfglinenbr == $id_no ]; then
					#echo $cfglinenbr $cfgline
					should_start=1
					start_line=$cfglinenbr
				fi

				# locate nearest }, in case we are in a infinite loop
				if [ $should_start -eq 1 ]; then
					if [[ ${#cfgline} -eq 1 ]] && [[ "$cfgline" = } ]]; then
						#echo $cfglinenbr $cfgline
						should_start=0
						break
					fi

					linux_line=$(echo -e $cfgline | sed 's/^[ \t]*//g')
					if [[ $linux_line == linux* ]]; then
						dno=$cfglinenbr
						#echo linux_line=$linux_line
						#echo dno=$dno
						break
					fi

				fi
			done <$bootconf

			# now we can change the values in "linux /vmlinuz-*"
			sed -i "${dno}s@linux.*@${params}@" $bootconf
		fi

	done <$inifilename
fi
#else
#	echo "is empty"
#fi
exit 0
