#!/bin/bash

# intel_lpmd confines workloads to low-power cores when the system looks idle,
# and a freshly resumed machine reads as idle: the wake burst (lock screen,
# unlock, apps catching up) then runs throttled on LP-E cores for 10+ seconds.
# Hold all cores open across sleep and hand control back 25 seconds after wake,
# keeping Performance mode off so PerformanceDef=-1 is respected.

ctl="${OMARCHY_LPMD_CONTROL:-/usr/bin/intel_lpmd_control}"
[[ -x $ctl ]] || exit 0
systemctl is-active --quiet intel_lpmd.service 2>/dev/null || exit 0

hook=$(readlink -f "$0")
unit="omarchy-lpmd-wake-boost-end"

restore_lpmd() {
  case $(timeout 2 powerprofilesctl get 2>/dev/null || true) in
    balanced | power-saver)
      timeout 2 "$ctl" AUTO >/dev/null 2>&1 || true
      ;;
  esac
}

case ${1:-} in
  pre)
    systemctl stop "$unit.timer" "$unit.service" >/dev/null 2>&1 || true
    timeout 2 "$ctl" OFF >/dev/null 2>&1 || true
    ;;
  post)
    systemctl stop "$unit.timer" "$unit.service" >/dev/null 2>&1 || true
    timeout 2 "$ctl" OFF >/dev/null 2>&1 || true
    if ! systemd-run --quiet --no-block --collect --unit="$unit" --on-active=25 \
      --timer-property=AccuracySec=1s \
      --property=Type=oneshot \
      --property=TimeoutStartSec=5s \
      "$hook" restore >/dev/null 2>&1; then
      restore_lpmd
    fi
    ;;
  restore)
    restore_lpmd
    ;;
esac

exit 0
