#!/bin/sh
## CC0 public domain
## 2024-02-07
## install:
##     $ mkdir -p ~/bin
##     $ cp -p barsan ~/bin
##     $ chmod +x ~/bin/barsan
## .xsession:
##     ~/bin/barsan xterm &
## .cwmrc:
##     autogroup 0 "barsan,barsan"
##     ignore barsan

BG='#160800'
FG='#fff0c0'
GEOMETRY='100x1+0-0'
FONT='xft:monospace:size=9'
SH='1.6'

NAME='barsan'
MESSAGE_COMPLETED='充電完了'
MESSAGE_CHARGING='充電中'
MESSAGE_LEFT='充電残'
MESSAGE_MINUTES='%3d分'

has_battery()
{
	test `apm -b` != 4
}

show_battery()
{
	local left=`apm -l`
	test "$left" = 100 && echo $MESSAGE_COMPLETED && return

	local minutes=`apm -m`
	local battery=""
	test "$minutes" != "unknown" && battery=`printf "$MESSAGE_MINUTES" $minutes`

	local status=`apm -a`
	test "$status" = 1 && echo "$MESSAGE_CHARGING $battery" && return
	test "$status" = 0 && echo "$MESSAGE_LEFT $battery" && return
}

show_workspace()
{
	local workspace=`xprop -root _NET_CURRENT_DESKTOP | grep '^.*=' | sed -e's/^.*= \(.*\)/\1/'`
	test -z "$workspace" && return
	echo "[${workspace}] "
}

show_title()
{
	local id="`xprop -root _NET_ACTIVE_WINDOW | grep 'window id' | sed -e's/^.*window id # \(0x.*\)/\1/'`"
	test -z "$id" && return
	test "$id" = '0x0' && return

	local xprop=`xprop -id "$id"` || return

	local wm_name=`echo "$xprop" | grep '^_NET_WM_NAME(UTF8_STRING) ='`
	if [ -z "$wm_name" ]
	then
		wm_name=`echo "$xprop" | grep '^WM_NAME(STRING) ='`
	fi
	echo "$wm_name" | sed -e's/^.* = "//' -e 's/"$//'
}

render()
{
	local buffer="`clear``tput cup 0 2`"
	if has_battery
	then
		buffer="$buffer`show_battery`"
		buffer="$buffer`tput cup 0 16`"
		buffer="$buffer | "
	fi
	buffer="$buffer`show_workspace``show_title` "
	buffer="$buffer`tput cup 0 0`"
	tput rmam
	printf '%s' "$buffer"
	tput smam
	sleep 0.5
}

case "$1" in
xterm)
	exec xterm -class "$NAME" -name "$NAME" -title "$NAME" \
		-bg "$BG" \
		-fg "$FG" \
		-fa "$FONT" \
		-geometry "$GEOMETRY" \
		-sh "$SH" \
		-e sh "$0" shell
	;;
shell)
	while true
	do
		render
	done
	;;
*)
	echo "usage: `basename $0` shell|xterm"
	;;
esac
