#!/bin/bash

while :; do
	status=$(cat /sys/class/power_supply/battery/status)
	
	if [ "$status" == "Not charging" ]; then
	    gpio write 0 1
	    gpio write 7 1
	    
	elif [ "$status" == "Discharging" ]; then
	  level=$(cat /sys/class/power_supply/battery/voltage_now)

	    if [ "$level" -ge 3900000 ]; then
		    gpio write 3 1
	    else
		    gpio write 3 0
	    fi

	    if [ "$level" -ge 3850000 ]; then
		    gpio write 2 1
	    else
		    gpio write 2 0
	    fi

	    if [ "$level" -ge 3820000 ]; then
		    gpio write 0 1
	    else
		    gpio write 0 0
	    fi
	    
	    if [ "$level" -ge 3750000 ]; then
		    gpio write 7 1
	    else
		    gpio write 7 0
	    fi
	    
	    if [ "$level" -ge 3700000 ]; then
		    gpio write 9 1
	    else
		    gpio write 9 0
	    fi
	    
	    if [ "$level" -ge 3600000 ]; then
		    gpio write 8 1
	    else
		    gpio write 8 0
	    fi

	    if [ "$level" -lt 3450000 ]; then
	    	    poweroff
	    fi
	
	else
	
	    level=$(cat /sys/class/power_supply/battery/capacity)

	    if [ "$level" -ge 95 ]; then
		    gpio write 3 1
	    else
		    gpio write 3 0
	    fi

	    if [ "$level" -ge 80 ]; then
		    gpio write 2 1
	    else
		    gpio write 2 0
	    fi

	    if [ "$level" -ge 65 ]; then
		    gpio write 0 1
	    else
		    gpio write 0 0
	    fi
	    
	    if [ "$level" -ge 40 ]; then
		    gpio write 7 1
	    else
		    gpio write 7 0
	    fi
	    
	    if [ "$level" -ge 25 ]; then
		    gpio write 9 1
	    else
		    gpio write 9 0
	    fi
	    
	    if [ "$level" -ge 12 ]; then
		    gpio write 8 1
	    else
		    gpio write 8 0
	    fi

	fi
	
	sleep 120
done
