#!/bin/sh

GLOBALCONFDIR="/etc/wmii"
export GLOBALCONFDIR

usage() {
    echo "usage: rc start|restart|stop" >&2
    echo "       rc reload [file]" >&2
    exit $1
}

getfile() {
    error=false

    if expr "$1" : '.*/' >/dev/null; then
        # $1 contains a slash
        if [ -r "$1" ]; then
            echo "$1"
        else
            error=true
        fi
    else
        # $1 contains no slash
        if [ -r "$HOME/.wmii/$1" ]; then
            echo "$HOME/.wmii/$1"
        elif [ -r "$GLOBALCONFDIR/$1" ]; then
            echo "$GLOBALCONFDIR/$1"
        else
            error=true
        fi
    fi

    if $error; then
        echo "error: $0: couldn't read $1" >&2
        usage 2
    fi
}

ixpmount() {
    $WRITE /ctl "bind /wmii $WMII_SOCKET"
    $WRITE /ctl "bind /bar $WMIBAR_SOCKET"
    $WRITE /ctl "bind /input $WMIINPUT_SOCKET"
    $WRITE /ctl "bind /keys $WMIKEYS_SOCKET"
}

util_setup() {
    for file in actions wmii bar keys input; do  # order matters
        . "$(getfile $file)"
        end_${file}_setup
    done
}

start() {
    if [ -f "$HOME/.wmii/.firstrun" ]; then
        rm "$HOME/.wmii/.firstrun"
        # this seems to be the first run
        xterm -bg black -fg grey -e 'man wmii' &  # display manpage
    fi

    # start wmii components:
    echo -n "Starting wmii utilities ..."
    wmifs -s $WMIFS_SOCKET &
    wmikeys -s $WMIKEYS_SOCKET &
    wmibar -s $WMIBAR_SOCKET 0,south,east,$LABEL_HEIGHT &
    wmiinput -s $WMIINPUT_SOCKET 0,south,east,$LABEL_HEIGHT &
    $WALLPAPER
    sleep 1
    ixpmount
    util_setup
    "$(getfile status.sh)" &  # run status loop
    echo "done."
}

reload() {
    echo -n "Reloading wmii configuration ..."
    case "$1" in
        "")
            util_setup
            ;;
        *actions|*bar|*input|*keys|*wmii)
            . "$(getfile "$1")"
            end_$(basename "$1")_setup
            ;;
        *)
            echo
            echo "error: $0: unsupported file"
            ;;
    esac
    echo "done."
}

stopp() {
    echo -n "Stopping wmii utilities ..."
    [ -f $STATUS_PIDFILE ] && \
        kill $(cat $STATUS_PIDFILE) >/dev/null 2>&1
    $WRITE /bar/ctl quit
    $WRITE /input/ctl quit
    $WRITE /keys/ctl quit
    $WRITE /ctl quit
    echo "done."
}

#---------------------------------------------------------------------

. "$(getfile rc.conf)"  # load variable definitions

if [ $# -eq 1 ] || { [ $# -eq 2 ] && [ "$1" = reload ]; }; then
    case "$1" in
    start)
        start
        ;;
    reload)
        reload "$2"
        ;;
    restart)
        stopp
        sleep 3  # wait for status.sh to exit
        start
        ;;
    stop)
        # the quit action causes wmii to execute "rc stop"
        stopp
        ;;
    *)
        usage 1
        ;;
    esac
else
    usage 1
fi
