#!/bin/sh

# rtc_battery.rpi5.sh
# 2026-04-19
# by Gernot Walzl

# https://www.raspberrypi.com/documentation/computers/raspberry-pi.html#real-time-clock-rtc

EDITOR=${EDITOR:-nano}

read_battery_voltage () {
  vcgencmd pmic_read_adc BATT_V
}

read_charging_voltage () {
  grep . /sys/class/rtc/rtc0/charging_voltage*
}

enable_charging () {
  # https://www.raspberrypi.com/documentation/computers/raspberry-pi.html#enable-battery-charging
  local CONFIG_TXT="/boot/firmware/config.txt"
  whiptail \
    --title "Edit $CONFIG_TXT" \
    --msgbox "# Charge the RTC battery at a given voltage
dtparam=rtc_bbat_vchg=3000000" \
    16 76
  $EDITOR "$CONFIG_TXT"
  echo "Reboot to apply the changes in config.txt."
}

case "$1" in
 'enable_charging')
  enable_charging
  ;;
 *)
  read_charging_voltage
  read_battery_voltage
esac