#!/bin/bash

DIR=`dirname $0`
. $DIR/helpers.sh
CMDLIST="$DIR/internal/cmd_list.txt"
SHCMD="$0"

trap ctrl_c INT

ctrl_c() {
	echo ; >/dev/null
}

init() {
	set -o emacs
	bind 'set show-all-if-ambiguous on'
	bind 'set completion-ignore-case on'
	bind 'TAB:dynamic-complete-history'

	cmds=`awk '{ print $2 }' $CMDLIST`
	for i in $cmds ; do
		history -s $i
	done
}

usage_exit() {
	echo "Incorrect usage or invalid cmd..."
	echo ;
	help
	exit
}

help() {
	echo "Usage1: $SHCMD ... provides a shell interface"
	echo "Usage2: $SHCMD <cmd_foobar> ... executes cmd_foobar on all the nodes"
	echo "Usage3: $SHCMD <cmd_foobar> <node_id> ... executes cmd_foobar on node_id only"
	echo ;
	echo "Possible commands:"
	echo "$cmds"
	echo ;
}

chk_exec_cmd() {
	cmd="$1"; shift
	str=`grep " $cmd$" $CMDLIST`
	[[ $? -ne 0 ]] && help && return 1
	line=${str/ */}
	if [ "$line" == "fw" ]; then
		$cmd $*
	else
		if [ "$1" == "" ]; then
			cmd_for_all_nodes ${line}_cmd "$cmd"
		else
			nodeid="$1"; shift;
			if [ "$1" != "" ]; then 
				args=":$*"
			fi
			${line}_cmd "$nodeid:$cmd$args"
            unset args
		fi
		echo ;
	fi
	history -s "$cmd"
}

usage()
{
	echo "Usage: $0 [-f <json>]"
	exit 1
}

cmdline_args() #XXX Currently unused but can be put to use in future.
{
	while getopts "f:" o; do
		case "$o" in
			f)
				output_fmt=$OPTARG
				;;
			*) 
				usage
				;;
		esac
	done
}

main() {
	wfpid=`wf_get_pid`
	[[ "$wfpid" == "" ]] && echo "Whitefield is stopped" && rem_msgq && exit
#	cmdline_args $*
#	shift $((OPTIND-1))
	init
	loop=1
	while [ $loop -ne 0 ]; do
		if [ "$1" == "" ]; then
			ans=""
			while [ "$ans" == "" ]; do
				read -e -p "wfsh# " ans
			done
		else
			loop=0
			ans="$1"
			shift
		fi
		chk_exec_cmd $ans $*
	done
}

#Processing starts here
main $*

