#!/bin/sh
#Wrapper script for lenovo_fix_coil_whine by JMC
#Created: 2026-01-07
#
#Might be a good idea to put this as sudoers.d so sudo always works.


NO_UDEV=0
if [ "$#" -ge 1 ]; then
    if [ "$1" = "--noudev" ]; then
        NO_UDEV=1
    fi
fi

if [ "$NO_UDEV" = "0" ]; then
    #If started by udev during boot, exit.
    #We only care about udev for AC to battery status change during usage, not boot.
    #Because on boot it used to hang for 2minutes by systemctl start, it didn't even
    #get to the program:
    UPTIME_SECS=$(echo `date '+%s'` "-"  `date '+%s' -d"$(uptime -s)"` | bc -ql)

    if [ "$UPTIME_SECS" -le "60" ]; then   #Using 1 minute threshold, that is 60 seconds.
        echo "Not running lenovo_fix_coil_whine by udev at boot (only $UPTIME_SECS uptime seconds)."
        exit 0
    fi
fi


#status can be "Discharging', "Not charging", "Charging".
AC_STATUS=$(cat /sys/class/power_supply/BAT0/status)

if [ "$AC_STATUS" = "Discharging" ]; then
    /usr/bin/systemctl stop lenovo_fix_coil_whine
else
    /usr/bin/systemctl start lenovo_fix_coil_whine
fi


