#!/bin/bash
# This script set FanPWM without cooling.

FULL_FLAG=0

change_fan_pwm()
{
    /opt/bmc/skynet/lua /opt/bmc/apps/mdbctl/service/mdbctl.lua call Fan_1_010103 bmc.kepler.Systems.Fan SetFanPWM 0 $1
    /opt/bmc/skynet/lua /opt/bmc/apps/mdbctl/service/mdbctl.lua call Fan_2_010103 bmc.kepler.Systems.Fan SetFanPWM 0 $1
    /opt/bmc/skynet/lua /opt/bmc/apps/mdbctl/service/mdbctl.lua call Fan_3_010103 bmc.kepler.Systems.Fan SetFanPWM 0 $1
    /opt/bmc/skynet/lua /opt/bmc/apps/mdbctl/service/mdbctl.lua call Fan_4_010103 bmc.kepler.Systems.Fan SetFanPWM 0 $1
}

if [ ! -d "/opt/bmc/apps/cooling" ]; then
    #等待thermal组件风扇识别完成后开始调速
    sleep 300
    source /etc/profile
    PWM=50
    while true; do
        INLET_TEMP=$(/opt/bmc/skynet/lua /opt/bmc/apps/mdbctl/service/mdbctl.lua getprop ThresholdSensor_InletTemp_0101 bmc.kepler.Systems.ThresholdSensor Reading)
        if [ $INLET_TEMP -le 20 ]; then
            NEW_PWM=40
        elif [ $INLET_TEMP -le 25 ]; then
            NEW_PWM=45
        elif [ $INLET_TEMP -le 30 ]; then
            NEW_PWM=65
        elif [ $INLET_TEMP -le 35 ]; then
            NEW_PWM=90
        else
            NEW_PWM=100
        fi
        CPUTEMP_1=$(/opt/bmc/skynet/lua /opt/bmc/apps/mdbctl/service/mdbctl.lua getprop CPU_1_010101 bmc.kepler.Systems.Processor.CPU TemperatureCelsius)
        CPUTEMP_2=$(/opt/bmc/skynet/lua /opt/bmc/apps/mdbctl/service/mdbctl.lua getprop CPU_2_010101 bmc.kepler.Systems.Processor.CPU TemperatureCelsius)
        if [ $CPUTEMP_1 -gt $CPUTEMP_2 ]; then
            MAX_TEMP=$CPUTEMP_1
        else
            MAX_TEMP=$CPUTEMP_2
        fi
        if [[ $MAX_TEMP -gt 103 && $FULL_FLAG -eq 0 ]]; then
            FULL_FLAG=1
            NEW_PWM=100
        fi
        if [[ $MAX_TEMP -le 85 && $FULL_FLAG -eq 1 ]]; then
            FULL_FLAG=0
        fi

        if [ $PWM -ne $NEW_PWM ]; then
            change_fan_pwm $NEW_PWM
            PWM=$NEW_PWM
        fi
        sleep 3
    done
fi
