#!/bin/sh

STOP_THRESHOLD=80
START_THRESHOLD=30

SHALL_CHARGE=0
IS_CHARGING=0

set_charger() {
	if [ $1 == 1 ]; then
		ectool chargecontrol normal
	else
		ectool chargecontrol idle
	fi
}


while true; do
	AC_STATE=`cat /sys/class/power_supply/AC/online`
	if [ $AC_STATE == "1" ]; then
		echo "on AC"
		BAT_LEVEL=`cat /sys/class/power_supply/BAT0/capacity`
		CURRENT=`cat /sys/class/power_supply/BAT0/current_now`
		echo "current=$CURRENT"
		if [ $CURRENT -gt 0 ]; then
			IS_CHARGING=1
		else
			IS_CHARGING=0
		fi
		if [ $BAT_LEVEL -gt $STOP_THRESHOLD ]; then
			echo "bat level > $STOP_THRESHOLD%"
			echo "charger disabling"
			SHALL_CHARGE=0
		elif [ $BAT_LEVEL -lt $START_THRESHOLD ]; then
			echo "bat level < $START_THRESHOLD%"
			echo "charger enabling"
			SHALL_CHARGE=1
		else
			echo "charger state OK, idling..."
		fi
	else
		echo "not on AC, idling..."
		SHALL_CHARGE=0
	fi
	echo $SHALL_CHARGE $IS_CHARGING
	if [ $SHALL_CHARGE != $IS_CHARGING ]; then
		set_charger $SHALL_CHARGE;
	fi
	sleep 10
done
