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

. /etc/profile

DEBUG=false
COOLING_PROFILE=$(get_setting "cooling.profile")
FAN_PWM="${DEVICE_PWM_FAN}"

log $0 "Setting profile to ${COOLING_PROFILE}"

function set_control() {
  log $0 "Set fan control to ${1}"
  if [ -e "${DEVICE_PWM_FAN}_enable" ]
  then
    echo ${1} >${DEVICE_PWM_FAN}_enable
  fi
}

trap "set_control 0 && exit 0" SIGHUP SIGINT SIGQUIT SIGABRT

if [ -e "/storage/.config/fancontrol.conf" ] && [ "${COOLING_PROFILE}" = "custom" ]
then
  log $0 "Loading configuration file" 2>/dev/null
  source /storage/.config/fancontrol.conf
  if [ ! $? = 0 ]
  then
    WARN="Custom fan profile could not be loaded, defaulting to auto."
    log $0 "${WARN}"
    COOLING_PROFILE="auto"
    set_setting cooling.profile auto
  fi
fi


if [ ! "${COOLING_PROFILE}" = "custom" ]
then
  if [ "${COOLING_PROFILE}" = "aggressive" ]; then
    MAXTEMP="75000"
    HIGHTEMP="65000"
    MIDTEMP="55000"
    LOWTEMP="45000"
    MINTEMP="35000"
  elif [ "${COOLING_PROFILE}" = "moderate" ]; then
    MAXTEMP="80000"
    HIGHTEMP="70000"
    MIDTEMP="60000"
    LOWTEMP="50000"
    MINTEMP="40000"
  elif [ "${COOLING_PROFILE}" = "quiet" ]; then
    # Quiet.
    MAXTEMP="85000"
    HIGHTEMP="75000"
    MIDTEMP="65000"
    LOWTEMP="55000"
    MINTEMP="45000"
  else
    # auto
    set_control 0 >/dev/null 2>&1
    exit 0
  fi
fi

CTEMP="1"

log $0 "Enabling fan control."
set_control 1 >/dev/null 2>&1

while true
  do
  INDEX=0
  CPU_TEMP=$(awk '{total += $1; count++} END {printf "%d", total/count}' ${DEVICE_TEMP_SENSOR})
  $DEBUG && log $0 "CPU TEMP: ${CPU_TEMP}" 2>/dev/null
  if (( "${CPU_TEMP}" > "${MAXTEMP}" )); then
    FSPEED="255"
    TEMP="${MAXTEMP}"
  elif (( "${CPU_TEMP}" > "${HIGHTEMP}" )); then
    FSPEED="196"
    TEMP="${HIGHTEMP}"
  elif (( "${CPU_TEMP}" > "${MIDTEMP}" )); then
    FSPEED="128"
    TEMP="${MIDTEMP}"
  elif (( "${CPU_TEMP}" > "${LOWTEMP}" )); then
    FSPEED="96"
    TEMP="${LOWTEMP}"
  elif (( "${CPU_TEMP}" > "${MINTEMP}" )); then
    FSPEED="64"
    TEMP="${MINTEMP}"
  else
    FSPEED="32"
    TEMP=0
  fi
  if (( ${TEMP} != ${CTEMP} )); then
    echo ${FSPEED} > ${FAN_PWM}
    CTEMP=${TEMP}
    $DEBUG && log $0 "Setting PWM FAN to ${FSPEED} at CPU Temp: ${CPU_TEMP}" 2>/dev/null
  fi
  sleep 3
done

log $0 "Disabling fan control."
set_control 0 >/dev/null 2>&1
