#!/bin/bash
# Copyright (c) 2022-2023, Dr Rahim Lakhoo, razman786@gmail.com.
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 
# for more details.
#
# You should have received a copy of the GNU General Public License along with
# this program. If not, see <https://www.gnu.org/licenses/>.
#

# display help
display_usage() {
  echo -e "\nUsage: $0 [OPTION]\n"
  echo -e "-e, --enable     enable BIOS thermal control\n"
  echo -e "-d, --disable     disable BIOS thermal control\n"
  echo -e "-s, --status     BIOS thermal control status\n"
}

# check whether user had supplied -h or --help.
if [[ ($1 == "--help") || $1 == "-h" ]]; then
  display_usage
  exit 0
fi

# enable BIOS fan control
if [[ ($1 == "--enable") || $1 == "-e" ]]; then
  status="enable"
fi

# disable BIOS fan control and enable i8kmon
if [[ ($1 == "--disable") || $1 == "-d" ]]; then
  status="disable"
fi

# get current thermal mode from libsmbios
if [[ ($1 == "--status") || $1 == "-s" ]]; then
  status="status"
fi

# enable BIOS fan control
if [[ $status == "enable" ]]; then
  # check i8kmon is available to stop
  if [[ -f "/etc/systemd/system/multi-user.target.wants/i8kmon.service" ]]; then
    systemctl stop i8kmon.service
  fi
  # check dell-bios-fan-control is available to stop
  if [[ -f "/etc/systemd/system/multi-user.target.wants/dell-bios-fan-control.service" ]]; then
    systemctl stop dell-bios-fan-control.service
  fi
  # check smbios-thermal-ctl is available from libsmbios
  if [[ "$(which smbios-thermal-ctl)" ]]; then
    smbios-thermal-ctl -i | grep -A 4 'Supported Thermal Modes'
    smbios-thermal-ctl -g | grep -A 1 'Current Thermal Modes'
  fi
# disable BIOS fan control and enable i8kmon
elif [[ $status == "disable" ]]; then
  # check dell-bios-fan-control is available to start - not all systems require this
  if [[ -f "/etc/systemd/system/multi-user.target.wants/dell-bios-fan-control.service" ]]; then
    systemctl start dell-bios-fan-control.service
  fi
  # check i8kmon is available to start
  if [[ -f "/etc/systemd/system/multi-user.target.wants/i8kmon.service" ]]; then
    systemctl start i8kmon.service
  fi
# get current thermal mode from libsmbios
elif [[ $status == "status" ]]; then
  # check smbios-thermal-ctl is available from libsmbios
  if [[ "$(which smbios-thermal-ctl)" ]]; then
    smbios-thermal-ctl -g | grep -A 1 'Current Thermal Modes' | (echo -n "Status " && cat)
  fi
fi
