#!/usr/bin/env bash

case "$IFO" in
    'L1')
	HOST='l1script0'
	;;
    'H1')
	HOST='h1guardian0'
	;;
    '')
	HOST='localhost'
	;;
    *)
	HOST="${IFO,,*}guardian0"
	;;
esac
HOST=${GUARDLOG_HOST:="$HOST"}
if [ -z "$HOST" ] ; then
    echo "GUARDLOG_HOST must be specified." >&2
    exit 1
fi
PORT=${GUARDLOG_PORT:=5555}

####################

PGRM="$0"

exec_server() {
    exec socat -d -d \
	TCP4-LISTEN:"$PORT",fork,reuseaddr \
	EXEC:"${PGRM} -g",stderr #,sigquit
}

exec_guardctrl() {
    local nodes

    if [ -z "$1" ] || [[ "$1" == '-' ]] ; then
	read -p "nodes: " nodes
    else
	nodes="$@"
    fi

    echo "$nodes"
    exec guardctrl log "$nodes"
}

exec_client() {
    local nodes

    if [ -z "$1" ] ; then
	nodes='-'
    else
	nodes="$@"
    fi

    #echo "$nodes" | exec socat -,ignoreeof TCP:"$HOST":"$PORT"
    (echo "$nodes" ; while sleep 60 ; do : ; done) \
	| netcat "$HOST" "$PORT"
}

####################

case "$1" in

    ####################
    # HELP
    '-h')
	pgrm=$(basename $0)
	cat <<EOF
usage: $pgrm [NODE...]
       $pgrm -s

Guardian log server/client.

For client, specify nodes whose log to tail as arguments.
For server, just run with '-s' option on guardian host.

GUARDLOG_PORT     server port
GUARDLOG_HOST     server host
EOF
	;;

    ####################
    # SERVER
    '-s')
	shift
	exec_server
	;;

    ####################
    # GUARDCTRL
    '-g')
	shift
	exec_guardctrl "$@"
	;;

    ####################
    # CLIENT
    *)
	if [ "$HOST" ] && [[ $(hostname) != "$HOST" ]] && [[ "$HOST" != 'localhost' ]] ; then
	    exec_client "$@"
	else
	    exec_guardctrl "$@"
	fi
	;;
esac
