#!/bin/sh
# PROVIDE: clawdie_live_power
# REQUIRE: FILESYSTEMS syslogd
# BEFORE: LOGIN
# KEYWORD: nojail
#
# 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.
#
# Scope: this selects a CPU C-state/frequency profile ONLY. It never suspends,
# sleeps, blanks the screen, or enables DPMS (screen-blank is handled separately
# by the no-blank stack: xorg.conf.d/40-clawdie-noblank.conf + the power-manager
# skel + clawdie-noblank-guard.sh). Both branches are wake-safe: rc.conf pins
# performance_cx_lowest AND economy_cx_lowest to C3, so neither the AC (0x01) nor
# battery (0x00) profile can drop into a deeper C-state that breaks the
# USB-backed resume path. Keep both at C3 on the live USB — do not deepen.

. /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"
