#!/usr/bin/env bash
set -o errexit
set -o pipefail

main() {
  if [[ -f "${1}" ]]; then
    exec 1>"${1}"
    shift
  fi

  if [[ -f /etc/default/thinkfan-confgen ]]; then
    source /etc/default/thinkfan-confgen
  fi

  : "${THINKFAN_LOWER_BOUND:=30}"
  : "${THINKFAN_STEP:=4}"

  printf '# thinkfan-confgen created %s\n' "$(date -u)"
  printf '# THINKFAN_LOWER_BOUND=%s\n' "${THINKFAN_LOWER_BOUND}"
  printf '# THINKFAN_STEP=%s\n\n' "${THINKFAN_STEP}"

  find /sys -type f -name 'temp*_input' | while read -r line; do
    if [[ "${line}" =~ thinkpad_hwmon ]]; then
      continue
    fi
    printf 'hwmon %s\n' "${line}"
  done

  printf '\ntp_fan /proc/acpi/ibm/fan\n\n'

  local halfstep="$((THINKFAN_STEP / 2))"
  local cur="${THINKFAN_LOWER_BOUND}"

  for level in 0 1 2 3 4 5 6 7; do
    if [[ "${level}" == 0 ]]; then
      printf '(0, 0, %s)\n' "${cur}"
      continue
    fi

    if [[ "${level}" == 7 ]]; then
      printf '(7, %s, 32767)\n' "$((cur - halfstep))"
      continue
    fi

    printf '(%s, %s, %s)\n' \
      "${level}" "$((cur - halfstep))" "$((cur + THINKFAN_STEP))"

    cur="$((cur + THINKFAN_STEP))"
  done
}

main "${@}"
