#!/bin/bash
# SecuBox LED Reset - Recovery from I2C bus hang
# Unloads and reloads the LED driver to reset the I2C device

set -e

LED_MODULE="leds_is31fl319x"
LED_SYSFS="/sys/class/leds"

log() {
    echo "[secubox-led-reset] $1"
}

# Check if running as root
if [ "$(id -u)" -ne 0 ]; then
    echo "Error: Must run as root" >&2
    exit 1
fi

# Stop LED services first
log "Stopping LED services..."
systemctl stop secubox-led-pulse.service 2>/dev/null || true
systemctl stop secubox-healthbump.timer 2>/dev/null || true

# Check if module is loaded
if lsmod | grep -q "$LED_MODULE"; then
    log "Unloading $LED_MODULE..."
    rmmod "$LED_MODULE" || {
        log "Error: Failed to unload module (may be in use)"
        exit 1
    }
    sleep 0.5
else
    log "Module $LED_MODULE not loaded"
fi

# Reload module
log "Loading $LED_MODULE..."
modprobe "$LED_MODULE" || {
    log "Error: Failed to load module"
    exit 1
}

# Wait for sysfs
sleep 1

# Verify LEDs are available
LED_COUNT=$(ls "$LED_SYSFS" 2>/dev/null | grep -c ":led" || echo 0)
if [ "$LED_COUNT" -gt 0 ]; then
    log "Success: $LED_COUNT LED channels available"

    # Quick test
    log "Testing LED write..."
    echo 100 > "$LED_SYSFS/green:led1/brightness" 2>/dev/null && {
        sleep 0.2
        echo 0 > "$LED_SYSFS/green:led1/brightness" 2>/dev/null
        log "LED test passed"
    } || {
        log "Warning: LED test failed"
    }
else
    log "Warning: No LED channels found after reset"
fi

# Restart LED services
log "Restarting LED services..."
systemctl start secubox-healthbump.timer 2>/dev/null || true
systemctl start secubox-led-pulse.service 2>/dev/null || true

log "Reset complete"
