#!/bin/sh

# Battery :
bat(){
	for battery in /sys/class/power_supply/BAT?*; do
		# If non-first battery, print a space separator.
		[ -n "${capacity+x}" ] && printf " "
		# Sets up the status and capacity
		case "$(cat "$battery/status" 2>&1)" in
			"Full") status="" ;;
			"Discharging") status="" ;;
			"Charging") status="" ;;
			"Not charging") status="" ;;
			"Unknown") status="" ;;
			*) exit 1 ;;
		esac
		capacity="$(cat "$battery/capacity" 2>&1)"
		# Will make a warn variable if discharging and low
		[ "$status" = "" ] && [ "$capacity" -le 25 ] && warn=" "
		# Prints the info
		printf "%s%s%d%%" "$status" "$warn" "$capacity"; unset warn
	done && printf "\\n"
}

# Date && clock :
dat(){
	date="$(date +"%a %d %b %H:%M"| sed 's/  / /g')"
	echo -e " $date"
}

# Cpu Temp :
tmp(){
	sensors | awk '/Core 0/ {print "" $3}'
}

# Cpu Usage :
cpu(){
	read cpu a b c previdle rest < /proc/stat
	prevtotal=$((a+b+c+previdle))
	sleep 0.5
	read cpu a b c idle rest < /proc/stat
	total=$((a+b+c+idle))
	cpu=$((100*( (total-prevtotal) - (idle-previdle) ) / (total-prevtotal) ))
	echo -e " $cpu%"
}

# Keybord Layout :
key(){
	kb="$(xkb-switch)" || exit 1
	echo " $kb"
}

# Screen Light :
lit(){
	#lit="$(xbacklight | sed 's/\..*//g')"
	#echo " $lit%"
	lit="$(brightnessctl | grep -oP '[^()]+%')"
	echo " $lit"	
}

# Memory :
mem(){
	mem="$(free -h | awk '/^Mem/ { print $3 }' | sed s/i//g)"
	echo -e " $mem"
}

# Volume :
vol(){
	[ $(pamixer --get-mute) = true ] && echo 🔇 && exit

	vol="$(pamixer --get-volume)"

	if [ "$vol" -gt "70" ]; then
		icon=""
	elif [ "$vol" -gt "30" ]; then
		icon=""
	elif [ "$vol" -gt "0" ]; then
		icon="" 
	else
		echo  && exit
	fi
	echo "$icon $vol%"
}

# Network traffic
nettrf(){
	
	update() {
		sum=0
		for arg; do
			read -r i < "$arg"
			sum=$(( sum + i ))
		done
		cache=${XDG_CACHE_HOME:-$HOME/.cache}/${1##*/}
		[ -f "$cache" ] && read -r old < "$cache" || old=0
		printf %d\\n "$sum" > "$cache"
		printf %d\\n $(( sum - old ))
	}

	rx=$(update /sys/class/net/[ew]*/statistics/rx_bytes)
	tx=$(update /sys/class/net/[ew]*/statistics/tx_bytes)

	printf " %4sB  %4sB\\n" $(numfmt --to=iec $rx) $(numfmt --to=iec $tx)	
}

while true; do

  xsetroot -name "[$(nettrf)][$(tmp)][$(cpu)][$(mem)][$(vol)][$(lit)][$(bat)][$(key)][$(dat)]"
  sleep 0.2
done &
