#!/bin/bash
# oxmc-battery-care: apply battery charge limits where the kernel and firmware
# expose them.  Does nothing on machines without a battery or without support.
# Override defaults in /etc/oxmc-platform/battery.conf (START, END, ENABLE,
# CONSERVATION, WAIT).
set -u
SYS=${OXMC_SYS:-/sys}
DMI=${OXMC_DMI:-/sys/class/dmi/id}
CONF=${OXMC_BATTERY_CONF:-/etc/oxmc-platform/battery.conf}

START=75
END=80
ENABLE=yes
CONSERVATION=yes
WAIT=8

if [ -r "$CONF" ]; then
  # shellcheck disable=SC1090
  . "$CONF"
fi

log() {
  echo "oxmc-battery-care: $*"
  logger -t oxmc-battery-care -- "$*" 2>/dev/null || true
}
setval() { { printf '%s\n' "$2" > "$1"; } 2>/dev/null; }

if [ "$ENABLE" != yes ]; then exit 0; fi
case "$START$END$WAIT" in
  ""|*[!0-9]*) log "START, END and WAIT must be whole numbers (see $CONF)"; exit 1 ;;
esac
if [ "$START" -ge "$END" ] || [ "$END" -gt 100 ]; then
  log "need START < END <= 100 (got $START/$END)"
  exit 1
fi

shopt -s nullglob
bats=("$SYS"/class/power_supply/BAT*)
if [ "${#bats[@]}" -eq 0 ]; then exit 0; fi

# MSI: the msi-ec driver does not always load by itself
vendor=$(cat "$DMI/sys_vendor" 2>/dev/null || true)
if [ "$SYS" = /sys ] && [[ $vendor == Micro-Star* ]] && [ ! -d /sys/module/msi_ec ]; then
  modprobe msi-ec 2>/dev/null || true
fi

has_support() {
  local b f
  for b in "${bats[@]}"; do
    if [ -e "$b/charge_control_end_threshold" ]; then return 0; fi
  done
  for f in "$SYS"/bus/platform/drivers/ideapad_acpi/*/conservation_mode; do
    if [ -e "$f" ]; then return 0; fi
  done
  return 1
}

# vendor drivers can appear a moment after boot
i=0
while ! has_support && [ "$i" -lt "$WAIT" ]; do
  sleep 1
  i=$((i + 1))
done

done_any=0
for b in "${bats[@]}"; do
  name=${b##*/}
  endf=$b/charge_control_end_threshold
  startf=$b/charge_control_start_threshold
  if [ ! -e "$endf" ]; then continue; fi
  start_failed=0
  if [ -e "$startf" ]; then
    setval "$startf" "$START" || start_failed=1
  fi
  setval "$endf" "$END" || log "$name: kernel rejected end threshold $END"
  # start may have been refused while the old end was lower; retry now
  if [ "$start_failed" = 1 ]; then
    setval "$startf" "$START" || log "$name: kernel rejected start threshold $START"
  fi
  cur_end=$(cat "$endf" 2>/dev/null || true)
  cur_start=$(cat "$startf" 2>/dev/null || true)
  log "$name: charge limit is now start=${cur_start:-n/a} end=${cur_end:-unknown}"
  done_any=1
done

# IdeaPad/Yoga/Legion/ThinkBook: fixed-threshold conservation mode
if [ "$done_any" = 0 ] && [ "$CONSERVATION" = yes ]; then
  for f in "$SYS"/bus/platform/drivers/ideapad_acpi/*/conservation_mode; do
    if setval "$f" 1; then
      log "$(basename "$(dirname "$f")"): battery conservation mode on"
      done_any=1
    fi
  done
fi

if [ "$done_any" = 0 ]; then
  log "no charge limit interface found (kernel or firmware does not expose one)"
fi
exit 0
