#!/bin/bash
#  Select and label a workspace

XMLOCAL=$HOME/.xmonad/lib/Local.hs

USAGE="$0 [-hdk] workspace [text...]
    -h: print help text
    -D: no default date/time
    -d: show date
    -k: kill label
    -l: list workspaces
    -L: no label, just switch
    -r: locate on the far right
"
[ -z "$1" ] && (echo "$USAGE"; exit)

. $HOME/.xmonad/lib/ws-utils.sh

# List labled workspaces
list () {
    ps x | grep [W]S= | sed 's/^.*-strftime //' | sed 's/%[a-zA-Z][- :]//g' | sort
}

KILL=false			# -k option: kill previous label and exit
LABEL=true			# Are we going to show a label?
STRFTIME=%H:%M 			# date-time format
POSITION=			# X position.  set to -0 for right-justified
while [ ! -z "$1" ]; do 
      case $1 in
	  (-h) echo "$USAGE"; exit;;
	  (-D) STRFTIME=""; shift;;
	  (-d) STRFTIME="%a %F %H:%M"; shift;;
	  (-k) KILL=true; shift;;
	  (-l) list; exit;;
	  (-L) LABEL=false; shift;;
	  (-r) POSITION=-0; shift;;
	  (*) break;;
      esac
done

N=$1; shift
if $LABEL; then
   COLORS="$(colors $N)"
   # kill any pre-existing bar with the same color code.
   for pid in $(ps x | egrep -e "[x]clock.*$COLORS" | first_number); do
       kill $pid;
   done

   if $KILL; then exit 0; fi

   # Get the x position from the xmonad local parameters if not set already:
   [ ! -z $POSITION ] || POSITION=+$(grep firstTopBarWidth $XMLOCAL | first_number)
fi
# Switch to the indicated workspace; allow time to get there.
#    we use wmctrl so that we don't have to fake a command with MOD+WS
wmctrl -s $(desktop_index $N)

if $LABEL; then
sleep 1
# Run the label program (xclock)
exec xclock -digital -geometry $POSITION+0 $COLORS -padding 0 \
            -strftime "WS=$N $STRFTIME $* " -name WS=$N-label &
fi
