#!/bin/sh
# Reseed /etc/config/battery when a firmware update ships a newer state-of-charge calibration.

LIVE_CONFIG="/etc/config/battery"
ROM_CONFIG="/usr/share/factory/battery.conf" # factory-default calibration shipped by this package
BACKUP="/etc/battery-calibration.bak"

sanitise_version() {
        case "$1" in
                ''|*[!0-9]*) echo 0 ;;
                *) echo "$1" ;;
        esac
}

file_version() {
        [ -f "$1" ] || { echo 0; return; }
        local raw_ver
        raw_ver=$(sed -nE "s/^[[:space:]]*option[[:space:]]+version[[:space:]]+'?([0-9]*)'?.*/\1/p" "$1" | head -n 1)
        sanitise_version "$raw_ver"
}

is_pinned() {
        [ -f "$LIVE_CONFIG" ] || return 1
        grep -qE "^[[:space:]]*option[[:space:]]+pinned[[:space:]]+'?1'?" "$LIVE_CONFIG"
}

if [ ! -f "$LIVE_CONFIG" ]; then
        if [ -f "$ROM_CONFIG" ]; then
                cp "$ROM_CONFIG" "$LIVE_CONFIG"
                chmod 0600 "$LIVE_CONFIG"
                logger -t battery-calibration "restored missing $LIVE_CONFIG from $ROM_CONFIG"
        fi
        exit 0
fi

if is_pinned; then
        logger -t battery-calibration "calibration is pinned, leaving it alone"
        exit 0
fi

live_version=$(file_version "$LIVE_CONFIG")
shipped_version=$(file_version "$ROM_CONFIG")

if [ "$shipped_version" -eq 0 ] || [ "$live_version" -ge "$shipped_version" ]; then
        exit 0
fi

cp "$LIVE_CONFIG" "$BACKUP"
cp "$ROM_CONFIG" "$LIVE_CONFIG"
chmod 0600 "$LIVE_CONFIG"

logger -t battery-calibration \
        "reseeded battery calibration v$live_version -> v$shipped_version from $ROM_CONFIG (backup kept at $BACKUP)"

exit 0
