#!/bin/bash

. __FFOO_INIT__
FFOO_INIPATH="__FFOO_INIPATH__"

ffoo import core
ffoo import ini
ffoo import recon


#
# self help
#

available_commands() {
    echo afk
    echo at
    echo back
    echo gone
    echo moving
    echo ooo
    echo wfh
    echo writing
}

usage() {
    cmd_hint=$(
        available_commands \
            | head -c -1 \
            | tr '\n' '|'
    )
    usage_is "$cmd_hint"
}


#
# querying
#

familiars_at() {
    #
    # daemons specific to $1 location plus the rest
    #
    test -n "$1" || usagef "location"
    iniread -p iam.running.at.$1 iam.ini
    iniread -p iam.running.at.ANYPLACE iam.ini
}

where_i_am() {
    #
    # what is my physical location?
    #
    if=$(iniread -p iam.using.if iam.ini)
    gwmac=$(arp | grep "^gateway\\>.*\\<$if\$" | tr ' ' '\n' | grep :)
    iniread -p iam.seeing.gw.$gwmac iam.ini || echo OUT
}


#
# subcommand handlers
#

i_am_afk() {
    #
    # away from keyboard; blocks until i'm back again
    #
    mocp --pause
    slock
}

i_am_at() {
    where_i_am
}

i_am_back() {
    #
    # returning to work (should be called by other subcommands)
    #
    local f fbin
    for f in $(familiars_at $(where_i_am));
    do
        fbin=${f/ */}
        pids_matching $f || $f &
    done
    klist || urxvt -e kinit
}

i_am_gone() {
    #
    # gone fishin'
    #
    kdestroy
    killall $(familiars_at $(where_i_am))
    i_am_afk
    i_am_back
}

i_am_moving() {
    #
    # to other train or dreamland, but localhost must sleep now
    #
    die "not implemented"   # hint: use zleep
}

i_am_ooo() {
    #
    # too dangerous to implement
    #
    die "not implemented"
}

i_am_wfh() {
    #
    # too dangerous to implement
    #
    die "not implemented"
}

i_am_writing() {
    #
    # writing in that language
    #
    set -x
    DISPLAY=:0 setxkbmap $1
}

cmd=$1

test -n "$cmd" || usage

available_commands | grep -qse ^$1 || usage

shift

i_am_$cmd $1