#!/bin/bash
# construct a launcher for sfwbar

mk_entry() {
	VAL="$1"
#	echo "$VAL" | grep -q '^/' && \
#	( cd ~/.config/sfwbar ; ln -sf "$VAL" . ) || \
	VAL=${VAL%\.*}
#	if [ "$(gsettings get org.gnome.desktop.interface gtk-theme | tr -d "'")" = 'Adwaita' ]; then
#		WW=$((${SIZE}*8/10))
#	else
		WW=${SIZE}
#	fi
	ACT="$2"
	ACT=$(echo "$ACT" | sed 's/%.*$//')
	cat >> ~/.config/sfwbar/launcher.widget << _B
  button {
    value = "$VAL"
    action = "$ACT"
    tooltip = "$3"
    css = "* { min-height: ${SIZE}px; min-width: ${WW}px; }"
  }
_B
}
export -f mk_entry

[ -f "$XDG_CONFIG_HOME/sfwbar/extrabar.conf" ] && \
POS=$(grep '^POS' $XDG_CONFIG_HOME/sfwbar/extrabar.conf)
POS=${POS/POS=/}
[ -z "$POS" ] && exit
SIZE=$(grep '^SIZE' $XDG_CONFIG_HOME/sfwbar/extrabar.conf)
SIZE=${SIZE/SIZE=/}
MON1=$(grep '^MON' $XDG_CONFIG_HOME/sfwbar/extrabar.conf)
MON1=${MON1/MON1=/}
read xx yy OLDMON <<<$(grep 'SetMonitor "launcher"' $HOME/.config/sfwbar/sfwbar.config | tr -d '"')
[ -z "$SIZE" ] && SIZE=36
LNR=$(grep -n 'SetMonitor "launcher"' $HOME/.config/sfwbar/sfwbar.config|cut -d ':' -f1)
sed -i "${LNR}s/${OLDMON}/${MON1}/" $HOME/.config/sfwbar/sfwbar.config
read -d ';' NR x POS_CFG <<<$(grep -n 'window#launcher' $HOME/.config/sfwbar/sfwbar.config)
NR=${NR%%\:*}
POS_CFG=${POS_CFG##*\ }
sed -i "${NR}s/${POS_CFG}/${POS}/" $HOME/.config/sfwbar/sfwbar.config

case $POS in
	left|right)BTN=bottom;;
	top|bottom)BTN=right ;;
esac

cat > ~/.config/sfwbar/launcher.widget << _S
layout {
_S
cat >> ~/.config/sfwbar/launcher.widget << _G
  css = "* { -GtkWidget-direction: $BTN; -GtkWidget-visible: true; }"
_G

while read entry; do
	[ "${entry:0:1}" = '#' ] && continue
	[ "${entry:0:4}" = 'POS=' ] && continue
	[ "${entry:0:4}" = 'SIZE' ] && continue
	[ "${entry:0:4}" = 'MON1' ] && continue
	a="${entry%%\|*}"
	b="${entry%\|*}"
	b="${b#*\|}"
	c="${entry##*\|}"
	mk_entry "$a" "$b" "$c"
done < $XDG_CONFIG_HOME/sfwbar/extrabar.conf

cat >> ~/.config/sfwbar/launcher.widget << _H
}
_H

