#!/bin/bash

## check illigal icons and icon-path
icon_check() # $conffile : wbar config file - It might be $HOME/.wbar
{
    local ifile=$conffile
    local icon_change=0
    local err_flag=0
    local tfile=/tmp/dot.wbar.`date +%y%m%d%H%M%S`
    local err_cmd=""
    local err_icon=""
    local default_png="/usr/share/wbar/iconpack/wbar.osx/default.png"
    local ipfix="i:"

    # make temp-file
    touch $tfile

    while read line; do
        case `echo "$line" | cut -d ":" -f1` in
            i)
		# icon-path
                icon_file=`echo "$line" | cut -d " " -f2`
		# png-image ?
                ping_file=`echo $line | grep -e ".png$"`
                if [ NOT"$ping_file" == "NOT"  ] || [ ! -f $icon_file ]; then
                    # caenged icon-path
                    line="$ipfix $default_png"
                    # set error message of icon-path
                    err_icon="$err_icon\t$icon_file\n"
                    # set flags
                    icon_change=1
                    err_flag=1
                fi
                # output a line(icon-path) to temp-file
                echo "$line" >> "$tfile"
                ;;
            c)
                if [ $icon_change == 1 ]; then
                    # set command names of icon error
                    err_cmd="$err_cmd""\t"`echo "$line" | cut -d " " -f2`"\n"
                    # reset flag
                    icon_change=0
                fi
                # output a line(exec command) to temp-file
                echo "$line" >> $tfile;;

            *)
                # output a line to temp-file
                echo "$line" >> $tfile;;
        esac
    done < "$ifile"

    if [ $err_flag == 1 ]; then
        # overwrite conf file
        cp -f "$tfile" "$ifile"
	# make error message
	err_msg="設定ファイル  '$conffile'  内で、\n\n$err_cmd\nに対応する以下のアイコンは、非サポート形式、又は指定場\n所に存在しません。\n\n$err_icon\n\nデフォルトのアイコンに置き換えました。\n(＊wbar がサポートするのは png 形式のアイコンのみです)\n\n必要な場合は 'wbar_util' か 'wbarconf' 又はテキスト\nエディタなどで、適正なアイコンに変更して下さい。\n(Enter 又は [OK] のクリックでこのウィンドウを閉じます)"
	case $LANG in
	    "ja_JP.UTF-8")
		nkf_opt="-w";;
	    "ja_JP.eucJP")
		nkf_opt="-e";;
	esac
	err_msg=`echo $err_msg | nkf "$nkf_opt"`
	if [ x"`echo $LANG | grep -e "ja_JP"`" == "x" ]; then
	    err_msg="Illegal icon-file or icon-path was found in wbar\nconfigfile '$conffile'.\n\n    At these commands:\n$err_cmd\n    Error icon-path:\n$err_icon\nDefault icon replaced them.\n(Notice: Only png format is supported.)\n\nPlease use wbar_utils or wbarconf (or your favorite\ntext editor) to customize again if you want ;-)"
	fi
        # display error message
        zenity --warning \
            --text="$err_msg"
    fi
    # remove temp-file
    rm "$tfile"
}

## settings of each desktop session
check_wbar_session_conf()
{
    if [ ! -d $HOME/.config/wbarsession/ ]; then
	mkdir -p $HOME/.config/wbarsession/
    fi
    if [ ! -f $HOME/.config/wbarsession/session_opts ]; then
	# write 'session_opts' file
	cat<<EOF > $HOME/.config/wbarsession/session_opts
## wbar_session standard options
##  preset value of each desktop
##
## Please set each option to your favorite value.
#
# GNOME
gnome_opts="-pos right -vbar -isize 38"
# xfce
xfce_opts="-pos right -vbar -isize 38"
# LXDE
lxde_opts="-pos right -vbar -isize 38"
# rox pinboard
rox_opts="-pos right -vbar -isize 38"
# WindowMaker
wmaker_opts="-pos bottom -hbar -jumpf 1.5 -isize 38 -zoomf 1.8 -filter 2 -fc 0x8877ffff"
# fluxbox
fluxbox_opts="-pos right -vbar -isize 38"
# icewm
icewm_opts="-pos top -jumpf 0.2 -isize 38"
# openbox
openbox_opts="-pos bottom -isize 38"
# twm
twm_opts="-pos right -vbar -isize 38"
EOF
    fi
}

## preset value of sessions
session_check()
{
    # check desktop sesson
    while [ 1 ]; do
        # GNOME
	desktopid=`pgrep gnome-session` > /dev/null
	if [ $? == 0 ] ; then
	    session_opts="$gnome_opts"
	    break
	fi
	# xfce
	desktopid=`pgrep xfce4-session` > /dev/null
	if [ $? == 0 ]; then
	    session_opts="$xfce_opts"
	    break
	fi
	# LXDE
	desktopid=`pgrep lxsession` > /dev/null
	if [ $? == 0 ]; then
	    session_opts="$lxde_opts"
	    break
	fi
	# rox pinboard
	ps xo cmd | grep -e "ROX-Filer *-" | grep -e \-p= | \
	    grep -ve \-p=^ -e "\-p= " > /dev/null
	if [ $? == 0 ]; then
	    session_opts="$rox_opts"
	    desktopid=`pgrep ROX-Filer`; echo $dsktopid
	    ### don't break
	fi
	# WindowMaker
	pgrep wmaker > /dev/null; [ $? == 0 ] && \
	    session_opts="$wmaker_opts" && break
	# fluxbox
	pgrep fluxbox > /dev/null; [ $? == 0 ] && \
	    session_opts="$fluxbox_opts" && break
	# icewm
	pgrep icewm-session > /dev/null && [ $? == 0 ] && \
	    session_opts="$icewm_opts" && break
	# openbox
	pgrep openbox > /dev/null && [ $? == 0 ] && \
	    session_opts="$openbox_opts" && break
	# twm
	pgrep twm > /dev/null && [ $? == 0 ] && \
	    session_opts="$twm_opts" && break
	break
    done
}


### start wbar_session

WBAR_SESSION_CONF=$HOME/.config/autostart/wbar.desktop

## run the auto-started wbar for your current session
if [ -f $WBAR_SESSION_CONF ]; then
    WBAR_SESSION=$(grep '^Exec=' $WBAR_SESSION
fi
        sed 's/^Exec=wbar_delay -startdelay [0-9.]*/wbar/')
    ## kill all wbar processes for restarting wbar
    killall wbar 2> /dev/null
    $WBAR_SESSION
else
    conffile=$HOME/.wbar

    ## vine default
    sec=3    # sleep seconds
    isz=48   # icon size
    zom=2.5  # zoom factor
    ani=5    # number of animated icons 

    sleepset=0
    hbarset=0
    options=""
    for i in $@; do
        case "$i" in
            "-help"|"-h"|"--help"|"-?")
                # wbar_session usage
                wbar -help | sed -e 's/Usage: wbar/Usage: wbar_session/' \
                    -e 's/ *-above-desk *run over a desktop app (ie: xfdesktop)//' \
		    -e 's/vertical bar/vertical bar\n   -hbar             horizontal bar/' \
                    | sed '/^$/d'
                echo "   -sleep  s         delay seconds"
                echo "# Default value: -sleep 3 -isize 48 -zoomf 2.5 -nanim 5"
		case $LANG in
		    "ja_JP.UTF-8")
			nkf_opt="-w";;
		    "ja_JP.eucJP")
			nkf_opt="-e";;
		    *)
			echo "# Default options are set first. Next, the content of "
			echo "# file \$HOME/.config/wbarsession/session_opts'"
			echo "# overwrites them. Option that you gave over writes them at end."
			echo "# See also '/usr/share/wbar/vine_readme_wbar.html'"
			echo "# (You can see it, if clicking 'README' item of wbar.)"
			exit;;
		esac
		echo "# wbar_sesson は、最初にデフォルト値を設定し、次にデスクトップ" \
                            | nkf "$nkf_opt"
		echo "# セッションこごとの設定を書かれたファイル、" \
                            | nkf "$nkf_opt"
		echo "#     '\$HOME/.config/wbarsession/session_opts'" \
                            | nkf "$nkf_opt"
		echo "# によりそれらは上書きされます。(このファイルはあなたの好みに" \
                            | nkf "$nkf_opt"
		echo "# あわせて書き換えしてもかまいません)" \
                            | nkf "$nkf_opt"
		echo "# コマンドラインから与えたオプションは最優先され、それらの内重複" \
                            | nkf "$nkf_opt"
		echo "# するものは全て上書きします。" \
                            | nkf "$nkf_opt"
		exit;;
            "-sleep")
                sleepset=1 ;;
 	    "-hbar")
		hbarset=1 ;;
            [0-9]*)
                # overwrite option value
                if [ $sleepset == 1 ]; then
                    sec="$i"
                    sleepset=0
                else
		    options="$options $i"
		fi
		;;
             -*|*)
                options="$options $i"
                ;;
        esac
    done

    if [ ! -f $conffile ]; then
        # output initial user config file
        wbar_gen
    fi

    ## Settings of '-above-desk' option
    options=`echo $options | sed 's/-above-desk//'`
    deskopt=""
    # nautilus
    pgrep nautilus > /dev/null; [ $? == 0 ] && \
	deskopt="-above-desk" && ps ux | \
        grep nautilus | grep -e --no-desktop; [ $? == 0 ] && deskopt=""
    # rox pinboard
    ps ux|grep ROX-Filer | grep  -e "-p=" > /dev/null && [ $? == 0 ] && \
        deskopt="-above-desk"
    # xfdesktop
    pgrep xfdesktop > /dev/null; [ $? == 0 ] && deskopt="-above-desk"
    # pcmanfm daemon
    ps ux | grep -e "pcmanfm *-d" > /dev/null && [ $? == 0 ] && \
        deskopt="-above-desk"

    # check icon-path in conf file
    icon_check

    # settings of deskto session options
    check_wbar_session_conf
    . $HOME/.config/wbarsession/session_opts

    # read 'session_opts' file
    session_check

    if [ $hbarset == 1 ]; then
	session_opts=`echo "$session_opts" | sed 's/-vbar//'`
    fi

    ### call wbar
    pkill -U `whoami` -x wbar
    all_opt="$deskopt -isize $isz -zoomf $zom -nanim $ani -bpress $session_opts $options"
    sleep "$sec"
    wbar $all_opt &

    # check desktop process (post processing) -----------------
    sleep "$sec"
    desktopid=""
    session_check

    while [ -n "`echo $desktopid | grep ' '`" ]; do 
	# If desktop process are not one, choice latest pid
	id="`echo $desktopid | cut -d ' ' -f 2`"
	desktopid=`echo $desktopid | sed 's/ //'`
    done;
    desktopid="$id"
    if [ -n "$desktopid" ]; then
	wbarid=`pgrep wbar`
	while [ -n "`echo $wbarid | grep ' '`" ]; do 
            # If wbar process are not one, choice latest pid
	    id="`echo $wbarid | cut -d ' ' -f 2`"
	    wbarid=`echo $wbarid | sed 's/ //'`
	done;
	wbarid="$id"
	if (( "$desktopid" > "$wbarid" )); then
	    # if desktop hides wbar, call wbar again
	    pkill -U `whoami` -x wbar
	    wbar $all_opt &
	fi
    fi
fi
