#!/bin/sh
# Put the BMC into manual fan control and pin the fans to a fixed speed.
#
# This is the ad-hoc override; ipmi-fancontrol.service runs the temperature-aware
# ipmi-fancontrol-daemon instead. Note that manual mode does not ramp under load.
set -eu

SCRIPT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
CONFIG=${IPMI_FANCONTROL_CONFIG:-$SCRIPT_DIR/conf/ipmi-fancontrol.conf}

if [ ! -r "$CONFIG" ]; then
    echo "Error: cannot read $CONFIG" >&2
    echo "Copy conf/ipmi-fancontrol.conf.example there and fill it in." >&2
    exit 1
fi

. "$CONFIG"

: "${IPMI_INTERFACE:=open}"
: "${FAN_SPEED:=0x15}"

ipmi() {
    if [ "$IPMI_INTERFACE" = "lanplus" ]; then
        ipmitool -I lanplus -H "$IPMI_HOST" -U "$IPMI_USER" -E "$@"
    else
        ipmitool -I open "$@"
    fi
}

if [ "$IPMI_INTERFACE" = "lanplus" ]; then
    : "${IPMI_HOST:?not set in $CONFIG}"
    : "${IPMI_USER:?not set in $CONFIG}"
    : "${IPMI_PASSWORD:?not set in $CONFIG}"
    # ipmitool -E reads the password from the environment, keeping it out of argv.
    export IPMI_PASSWORD
fi

# Disable the BMC's automatic fan curve, then apply the fixed speed to all fans.
ipmi raw 0x30 0x30 0x01 0x00
ipmi raw 0x30 0x30 0x02 0xff "$FAN_SPEED"
