#!/bin/bash -e
# PiSugar UPS Support - Native I2C Driver
#
# This enables native I2C support for PiSugar UPS devices.
# NO pisugar-server daemon is required - we communicate directly with
# the battery management chip via I2C for minimal CPU usage.
#
# Supported hardware:
# - PiSugar 2 (4-LEDs) - IP5209 chip at I2C address 0x75
# - PiSugar 2 Pro - IP5209 chip at I2C address 0x75
# - PiSugar 3 / 3 Plus - IP5312 chip at I2C address 0x57
#
# Features:
# - Battery voltage/current/percentage reading
# - Charging status detection
# - Button tap detection
# - RTC alarm for scheduled wake-up (SD3078 at 0x32)
# - Force shutdown capability
#
# Disable this substage by creating a SKIP file if you don't use PiSugar

echo "Configuring native PiSugar I2C support..."

# Ensure I2C is enabled (already done in 04-dangerous-pi, but verify)
BOOT_CONFIG="/boot/firmware/config.txt"
if [ ! -f "$BOOT_CONFIG" ]; then
    BOOT_CONFIG="/boot/config.txt"
fi

if [ -f "$BOOT_CONFIG" ]; then
    if ! grep -q "^dtparam=i2c_arm=on" "$BOOT_CONFIG"; then
        echo "dtparam=i2c_arm=on" >> "$BOOT_CONFIG"
        echo "Enabled I2C in boot config"
    fi
fi

# Ensure i2c-dev module loads at boot
mkdir -p /etc/modules-load.d
echo "i2c-dev" > /etc/modules-load.d/i2c-dev.conf

# smbus2 is already installed by 04-dangerous-pi stage
# Verify it's available
python3 -c "import smbus2; print('smbus2 available')" || {
    echo "Installing smbus2..."
    pip3 install --break-system-packages smbus2==0.4.3
}

# i2c-tools installed by 00-apt-setup stage

echo ""
echo "=============================================="
echo "PiSugar Native I2C Support Configured"
echo "=============================================="
echo ""
echo "The Dangerous Pi backend will automatically detect PiSugar hardware"
echo "via I2C when UPS_TYPE=auto (default) is set."
echo ""
echo "Supported PiSugar models:"
echo "  - PiSugar 2 (4-LEDs) at I2C 0x75"
echo "  - PiSugar 2 Pro at I2C 0x75"
echo "  - PiSugar 3 / 3 Plus at I2C 0x57"
echo ""
echo "RTC (SD3078) detected at I2C 0x32 for wake-up alarms"
echo ""
echo "NOTE: pisugar-server daemon is NOT installed."
echo "This native driver uses <1% CPU vs 350%+ for the daemon."
echo ""
