#!/bin/bash
# How to run this script
# sudo curl https://www.bi7jta.org/files/MMDVM_Firmware/repeater_HAT/upgrade_repeater_Baud460800_OldCode_v20250831_just-enable-DMR_DSTAR_YSF.sh | sudo sh

sudo mount -o remount,rw / ;

# suit bookworm OS
# gpio front/back compat. for pi5 and older Pi SBCs; since Pi5 has its own GPIO chip (gpiochip4 [pinctrl-rp1])
# also fixes new kernels on the RPi family (Thank you WPSD team)
#
getGPIOpinMaps=$(ls -la /sys/class/gpio/gpiochip* | grep "0000.gpio" | sed -n "s/.*gpiochip\([0-9]*\).*/\1/p" | tail -n 1)
 
#getGPIOpinMaps=${getGPIOpinMaps/504/0}

pin20=$((getGPIOpinMaps + 20))
pin21=$((getGPIOpinMaps + 21))
 
echo "pin20: ${pin20}"
echo "pin21: ${pin21}"

cd ~
hex_file="mmdvm_f4_OldCode_v20250831_just-enable-DMR_DSTAR_YSF.bin"
echo "hex_file:${hex_file}"
rm -f ./${hex_file}
curl -OL https://www.bi7jta.org/files/MMDVM_Firmware/repeater_HAT/${hex_file};
curl -OL https://www.bi7jta.org/files/MMDVM_Firmware/repeater_HAT/stm32flashV5; 

sudo chmod +x stm32flashV5;

echo "Stopping Pi-Star Services..." 

sudo systemctl stop pistar-watchdog.timer
sudo systemctl stop pistar-watchdog.service
sudo systemctl stop mmdvmhost.timer
sudo systemctl stop mmdvmhost.service
sleep 3

echo "Killing any remaining MMDVMHost processes..."
sudo killall MMDVMHost
sudo killall MMDVMHost_NoOLED
sudo killall MMDVMHost_Adafruit

echo "Starting Flashing..."

sudo ~/stm32flashV5 -v -w ~/${hex_file}  -R  -i ${pin20},-${pin21},${pin21}:-${pin20},-${pin21},${pin20} /dev/ttyAMA0;

	#if [ "$VERBOSE" = 1 ] ; then
	#    /usr/local/bin/firmware/utils/stm32flash-${stmVer} -i ${pin20},-${pin21},${pin21}:-${pin20},${pin21} /dev/ttyAMA0 >/dev/null 2>&1
	#    /usr/local/bin/firmware/utils/stm32flash-${stmVer} -v -w /usr/local/bin/firmware/${firmware_file} -g 0x0 -R /dev/ttyAMA0
	#else
	#    /usr/local/bin/firmware/utils/stm32flash-${stmVer} -i ${pin20},-${pin21},${pin21}:-${pin20},${pin21} /dev/ttyAMA0 >/dev/null 2>&1
	#    output=$(eval /usr/local/bin/firmware/utils/stm32flash-${stmVer} -v -w /usr/local/bin/firmware/${firmware_file} -g 0x0 -R /dev/ttyAMA0 2>&1)

sleep 3

echo "Starting Pi-Star Services..."

sudo mount -o remount,ro /

sudo systemctl start pistar-watchdog.timer
sudo systemctl start pistar-watchdog
sudo systemctl start mmdvmhost.timer
sudo systemctl start mmdvmhost

echo "Finnished..."




