#!/bin/bash

####################################################################################
##
##  Check if every config in server.conf is same on all hosts
##
##  ./check_config_on_all_hosts.sh [KEY]
##
##  If KEY is provoded, checks KEY only. Otherwise, checks all keys
##
#####################################################################################

if [[ ! -f "$HOME/.jaguarhome" ]]; then
	echo "Jaguar has not been installed, quit"
	exit 1
fi

unset LD_LIBRARY_PATH

JAGUAR_HOME=`cat $HOME/.jaguarhome`
hostfile="$JAGUAR_HOME/conf/cluster.conf"
allhosts=`grep -v '#' $hostfile|grep -v '@'`

if [[ ! -f "$hostfile" ]]; then
    echo "$hostfile is not found, exit"
    exit 1
fi

myips=`hostname -I`

function checkit()
{
	key=$1
	h=$2
	jh=$3

    if echo $myips | grep -q $h; then
	    val=`grep $key $jh/conf/server.conf|grep -v '#'|cut -d'=' -f2|tr -d ' '`
    else
	    val=`ssh $h "grep $key $jh/conf/server.conf|grep -v '#'|cut -d'=' -f2|tr -d ' '"`
    fi

    echo "$h $key=$val"
}


####### main ####
KEY=$1
if [[ "x$KEY" = "x" ]]; then
	keys=`grep '=' $JAGUAR_HOME/conf/server.conf| grep -v '#'|cut -d'=' -f1|tr -d ' '`
else
	keys=$KEY
fi

for h in $allhosts
do
    if echo $myips | grep -q $h; then
        jh=$JAGUAR_HOME
    else
        jh=`ssh $h 'if [ -f ~/.jaguarhome ]; then cat ~/.jaguarhome; else echo $HOME/jaguar; fi'`
    fi

    for k in $keys; do
        checkit $k $h $jh &
    done

    wait
    echo
done

exit 0

