#!/bin/bash
# How to run this script
# sudo curl https://www.bi7jta.org/files/MMDVM_Firmware/repeater_HAT/reboot_flash/2.1.enter_flash_mode-not-need-poweroff.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}"

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
sudo systemctl stop nextiondriver.service #Must stop NextionDriver

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

echo "${pin20}" > /sys/class/gpio/export  
#sleep 1
echo "${pin21}" > /sys/class/gpio/export  
#sleep 1
echo "out" > /sys/class/gpio/gpio${pin20}/direction   
#sleep 1
echo "out" > /sys/class/gpio/gpio${pin21}/direction  
#####执行到这一步，进入reset状态，PWR/COS灯亮

#sleep 10
echo "0" > /sys/class/gpio/gpio${pin21}/value #（21写入低电平）  
sleep 0.01
echo "1" > /sys/class/gpio/gpio${pin20}/value #（20写入高电平）

#等待1s 中继板电容充分放电
#whait enough to discharge C3
sleep  0.01
echo "1" > /sys/class/gpio/gpio${pin21}/value #再将21写入高电平,进入刷机状态，标志“ACT红灯亮” #230对应树莓派20
sleep 0.05


echo "========================================================================================================="
echo "======== Enter flash mode done, please plug the MMDVM HAT to Raspberry Pi (GPIO 40 PINS)================="
echo "======== Check if your MMDVM HAT LED status same as ====================================================="
echo "======== https://wiki.bi7jta.org/wiki/index.php?title=File:Enter_Recovery_mode_V3F4.png ================"
echo "======== Then run the flash script ================ ====================================================="
echo "========================================================================================================"
 




