#!/bin/bash
# SPDX-License-Identifier: GPL-2.0
# Copyright (C) 2023 JELOS (https://github.com/JustEnoughLinuxOS)

. /etc/profile

###
### On startup the device will run at the default EPP,
### this is desired behavior. Check if we have an EPP
### setting, and set it.
###

if [ $# -eq 0 ] || [ "$1" == "boot" ]
then
  PROFILE=$(get_setting system.power.epp)
  if [ -z "${PROFILE}" ]
  then
    PROFILE="balance_performance"
    set_setting system.power.epp ${PROFILE}
  fi
else
  PROFILE=$1
fi
CPU_VENDOR=$(cpu_vendor)

case ${CPU_VENDOR} in
  AuthenticAMD)
    PSTATE="amd_pstate"
    STATUS="active"
  ;;
  GenuineIntel)
    PSTATE="intel_pstate"
    STATUS="passive"
  ;;
esac

if [ -f "/sys/devices/system/cpu/${PSTATE}/status" ]
then
  echo ${STATUS} >/sys/devices/system/cpu/${PSTATE}/status
  while [ ! -f /sys/devices/system/cpu/cpufreq/policy0/energy_performance_preference ]
  do
    sleep .25
  done
  case ${PROFILE} in
    *)
      for POLICY in $(find /sys/devices/system/cpu/cpufreq -name policy[0-9]*)
      do
        echo ${PROFILE} >${POLICY}/energy_performance_preference 2>/dev/null
      done
    ;;
  esac
fi
