#!/bin/sh

command="`basename \"$0\"`"
fluxdir="$HOME/.fluxbox"
startup="$fluxdir/startup"

while [ $# -gt 0 ]; do
    case "$1" in
        -c|--config)
            if [ $# -lt 2 ]; then
                echo "$command:error, missing argument"
                exit 1
            fi
            shift
            startup=$1
        ;;
        -h|--help) cat <<EOF
Usage: $command [-h] [-c startupfile]
EOF
        exit
        ;;
    esac
    shift
done

# keys update (for 1.1.1 -> 1.3.0 (Vine Linux))
if [ -f "$fluxdir/keys" ]; then
    if [ ! `grep "fluxbox-1.3" "$fluxdir/fb_release" 2> /dev/null` ]; then
	echo "! ---------- update by startfluxbox(1.3.0) ---------" >> "$fluxdir/keys"
	echo "OnLeftGrip Move1  :StartResizing bottomleft" >> "$fluxdir/keys"
	echo "OnRightGrip Move1 :StartResizing bottomright" >> "$fluxdir/keys"
	echo "OnTitlebar Mouse1 :MacroCmd {Raise} {Focus} {StartMoving}" >> "$fluxdir/keys"
    fi
fi

if [ -x "$startup" ]; then
    exec "$startup"
elif [ -r "$startup" ]; then
    exec sh "$startup"
else
    if [ ! -d $fluxdir ]; then
        mkdir -p "$fluxdir/backgrounds" "$fluxdir/styles" "$fluxdir/pixmaps"
    fi
    if [ ! -r "$startup" ]; then
        ( cat << EOF
#!/bin/sh
#
# fluxbox startup-script:
#
# Lines starting with a '#' are ignored.

# Change your keymap:
xmodmap "$HOME/.Xmodmap"

# Applications you want to run with fluxbox.
# MAKE SURE THAT APPS THAT KEEP RUNNING HAVE AN ''&'' AT THE END.
#
# unclutter -idle 2 &
# wmnd &
# wmsmixer -w &
# idesk &

# The purpose of delay execution (sleep & exec) is to start fluxbox faster.
#
# sleep 8 && rox -p=std_desk -t=my_panel
# sleep 15 &&  exec gkrellm -w &

# --- Initial change-rootcmd script
if ! [ -a $HOME/.fluxbox/change-rootcmd ]; then
   echo "#!/bin/bash" > $HOME/.fluxbox/change-rootcmd
   echo "exec /usr/share/fluxbox/change-rootcmd" >> $HOME/.fluxbox/change-rootcmd
   chmod u+x $HOME/.fluxbox/change-rootcmd
fi

# --- Copy 'UserMenu' Directory to $HOME ---
if ! [ -d $HOME/.fluxbox ]; then
    mkdir $HOME/.fluxbox
fi
if ! [ -a $HOME/.fluxbox/UserMenu ]; then
    if [ -f $HOME/.fluxbox/usermenu ]; then
        cp $HOME/.fluxbox/usermenu $HOME/.fluxbox/usersubmenu
    fi
    cp -a /usr/share/fluxbox/UserMenu  $HOME/.fluxbox
fi

# --- STYLE Backward compatibility script ---
if ! [ -a $HOME/.fluxbox/fb_backcompat ]; then
    echo "back_compat=true" > $HOME/.fluxbox/fb_backcompat
fi
. $HOME/.fluxbox/fb_backcompat
if [ \$back_compat == true ]; then
    if [ -x $HOME/.fluxbox/change-rootcmd ]; then
	$HOME/.fluxbox/change-rootcmd &
    elif [ -x /usr/share/fluxbox/change-rootcmd ]; then
	/usr/share/fluxbox/change-rootcmd &
    fi
fi

# --- Welcome message ---
/usr/share/fluxbox/fb_welcome &

# And last but not least we start fluxbox.
# Because it is the last app you have to run it with ''exec'' before it.

exec fluxbox
# or if you want to keep a log:
# exec fluxbox -log "$fluxdir/log"
EOF
    ) > "$startup"
    fi
    chmod 644 "$startup"
    exec sh "$startup"
fi
