#!/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
}

start_familiar() {
    #
    # start familiar as indicated by ini file (unless running)
    #
    local f=$1
    pids_matching $f && return 0
    local like=$(iniread -p iam.starting.like.this.$f iam.ini)
    debug -v f like
    if test -n  "$like";
        then
            $like &
        else $f &
    fi
}

set_status() {
    #
    # set public status $1 by command in ini file
    #
    local what=$1
    iniread -p iam.saying.like.this.$what iam.ini | bash
}


#
# subcommand handlers
#

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

i_am_at() {
    #
    # Just say where I am
    #
    where_i_am
}

i_am_back() {
    #
    # returning to work (should be called by other subcommands)
    #
    local f
    for f in $(familiars_at $(where_i_am));
    do
        start_familiar $f
    done
    set_status "back"
    klist || urxvt -e kinit
}

i_am_gone() {
    #
    # gone fishin'
    #
    kdestroy
    set_status "gone"
    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