#!/bin/bash
# Power Management for SaltyBot Phone Node

set -e

BATTERY_CRITICAL=15
BATTERY_LOW=25
CURRENT_MODE="normal"

log_msg() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1"
}

get_battery() {
    termux-battery-status 2>/dev/null | grep -o '"percentage":[0-9]*' | cut -d: -f2 || echo "50"
}

monitor() {
    BATTERY=$(get_battery)
    log_msg "Battery: ${BATTERY}%  Mode: $CURRENT_MODE"

    if [ "$BATTERY" -le "$BATTERY_CRITICAL" ]; then
        if [ "$CURRENT_MODE" != "critical" ]; then
            log_msg "Switching to CRITICAL mode"
            CURRENT_MODE="critical"
        fi
    elif [ "$BATTERY" -le "$BATTERY_LOW" ]; then
        if [ "$CURRENT_MODE" != "low_power" ]; then
            log_msg "Switching to LOW POWER mode"
            CURRENT_MODE="low_power"
        fi
    else
        if [ "$CURRENT_MODE" != "normal" ]; then
            log_msg "Switching to NORMAL mode"
            CURRENT_MODE="normal"
        fi
    fi
}

log_msg "Power management started"
while true; do
    monitor
    sleep 30
done
