#!/bin/sh
# -*- mode: sh; tab-width: 8; encoding: utf-8-unix -*-

# retval on stdout - messages on stderr
. /usr/local/bin/usr_local_tput.bash

prog=`basename $0 .bash`
PREFIX=/usr/local
ROLE=toxcore
AnsI=AnsI

# quiet
[ "$#" -eq 0 ] && exit 1
VARIABLE=$1
shift
[ "$#" -eq 0 ] && base=`hostname` ||  base=$1

[ -f $PREFIX/etc/testforge/testforge.bash ] && . $PREFIX/etc/testforge/testforge.bash

[ -n "$PLAY_ANSIBLE_SRC" ] || PLAY_ANSIBLE_SRC=$BASE_ANSIBLE_SRC
[ -n "$PLAY_ANSIBLE_SRC" ] || PLAY_ANSIBLE_SRC=/mnt/o/data/TestForge/src/ansible
[ -z "$PLAY_ANSIBLE_SRC" ] && ERROR  export "PLAY_ANSIBLE_SRC" >&2 && exit 3
[ ! -d "$PLAY_ANSIBLE_SRC" ] && ERROR  ! -d "PLAY_ANSIBLE_SRC" >&2 && exit 4
[ ! -f "$PLAY_ANSIBLE_SRC"/hosts.yml ] && ERROR  ! -f "PLAY_ANSIBLE_SRC"/hosts.yml >&2  && exit 4

DBUG ansible-inventory -i $PLAY_ANSIBLE_SRC/hosts.yml \
		      --playbook-dir=$PLAY_ANSIBLE_SRC \
		      --host=$base >&2
ansible-inventory -i $PLAY_ANSIBLE_SRC/hosts.yml \
		      --playbook-dir=$PLAY_ANSIBLE_SRC \
		      --host=$base >> /tmp/${AnsI}$$.json 2> /tmp/${AnsI}$$.err
    retval=$?
    if [ $retval -eq 0 ] ; then
	[ ! -s /tmp/${AnsI}$$.json ] && ERROR empty /tmp/${AnsI}$$.json >&2 && exit 4
	#!? export
	VALUE=`jq .$VARIABLE < /tmp/${AnsI}$$.json | sed -e  's/,//'|xargs echo 2>/tmp/${AnsI}$$.err`
	jretval=$?
	if [ $jretval -eq 0 ] ; then
	    [ -n "$DEBUG" ] &&  DBUG "$prog base=$base VALUE=$VALUE" >&2
	    [ "$VALUE" = "null" ] && VALUE=""
	    echo -n "$VALUE"
	else
	    WARN $VARIABLE jretval=$jretval /tmp/${AnsI}$$.err >&2
	    exit 7$retval
	fi
    else
	ERROR $VARIABLE  retval=$retval /tmp/${AnsI}$$.json /tmp/${AnsI}$$.err >&2
	cat /tmp/${AnsI}$$.err >&2
	exit 8
    fi
#    rm -f /tmp/${AnsI}$$.json

exit 0
