#!/bin/sh
# Clawdie operator USB live power baseline.
# Applies the rc.conf power_profile C-state policy once at boot. FreeBSD's
# power_profile service is marked nostart and normally runs only when devd sees
# an AC-line transition, so a live USB can otherwise sit at the firmware/default
# C-state until AC is unplugged/replugged.

# PROVIDE: clawdie_live_power
# REQUIRE: FILESYSTEMS syslogd
# BEFORE: LOGIN
# KEYWORD: nojail

. /etc/rc.subr

name="clawdie_live_power"
rcvar="${name}_enable"
start_cmd="${name}_start"
stop_cmd=":"
status_cmd="${name}_status"
extra_commands="status"

LOG_FILE="/var/log/clawdie-live-power.log"

_power_log()
{
    printf '%s %s\n' "$(date '+%Y-%m-%dT%H:%M:%S')" "$*" >>"${LOG_FILE}" 2>/dev/null || true
}

_power_state_arg()
{
    _acline="$(sysctl -n hw.acpi.acline 2>/dev/null || echo unknown)"
    case "${_acline}" in
        0)
            echo 0x00
            ;;
        1)
            echo 0x01
            ;;
        *)
            # Desktops/VMs may not expose hw.acpi.acline. Use performance
            # profile so rc.conf's performance_cx_lowest still applies.
            echo 0x01
            ;;
    esac
}

clawdie_live_power_start()
{
    : >>"${LOG_FILE}" 2>/dev/null || true

    _state="$(_power_state_arg)"
    _power_log "applying power_profile ${_state}"

    if service power_profile "${_state}" >>"${LOG_FILE}" 2>&1; then
        _power_log "power_profile ${_state} applied"
    else
        _power_log "WARN: power_profile ${_state} failed"
    fi

    _cx="$(sysctl -n hw.acpi.cpu.cx_lowest 2>/dev/null || echo unavailable)"
    _freq="$(sysctl -n dev.cpu.0.freq 2>/dev/null || echo unavailable)"
    _power_log "hw.acpi.cpu.cx_lowest=${_cx} dev.cpu.0.freq=${_freq}"

    return 0
}

clawdie_live_power_status()
{
    if [ -s "${LOG_FILE}" ]; then
        echo "${name}: one-shot power policy; last run log tail:"
        tail -n 5 "${LOG_FILE}"
        return 0
    fi
    echo "${name}: not yet run this boot (no log at ${LOG_FILE})"
    return 1
}

load_rc_config "$name"
: "${clawdie_live_power_enable:=YES}"
run_rc_command "$1"
