#!/bin/sh
# Copyright (c) 2016 Oracle and/or its affiliates. All Rights Reserved.
# Copyright (c) International Business Machines  Corp., 2000
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of
# the License, or (at your option) any later version.
#
# This program is distributed in the hope that it would be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# PURPOSE: To test the basic functionality of the rwhod daemon using the
#          `rwho` and `ruptime` commands.
#

TCID=rwho01
TST_TOTAL=25
TST_CLEANUP="do_cleanup"

. test_net.sh

LHOST_PID=
RHOST_PID=

do_setup()
{
	tst_check_cmds cut hostname killall rwho ruptime

	LHOST=$(hostname | cut -f1 -d.)

	pgrep -x rwhod > /dev/null
	if [ $? -ne 0 ]; then
		tst_resm TINFO "Starting rwhod on $LHOST"
		ROD rwhod
		LHOST_PID=$(pgrep -x rwhod)
		[ -z "$LHOST_PID" ] && \
			tst_brkm TBROK "Unable to start rwhod on $LHOST"
	fi

	tst_rhost_run -c "pgrep -x rwhod" > /dev/null
	if [ $? -ne 0 ]; then
		tst_resm TINFO "Starting rwhod on $RHOST"
		tst_rhost_run -s -c "rwhod"
		RHOST_PID=$(tst_rhost_run -c "pgrep -x rwhod")
		[ -z "$RHOST_PID" ] && \
			tst_brkm TBROK "Unable to start rwhod on $RHOST"
	fi

	RHOSTNAME=$(tst_rhost_run -c "hostname | cut -f1 -d.")
	[ "$RHOSTNAME" ] || tst_brkm TBROK "Unable to determine RHOSTNAME"
}

do_test()
{
	rwho -a | grep -q $LHOST || \
		tst_brkm TFAIL "$LHOST isn't in rwho output"
	rwho -a | grep -q $RHOSTNAME || \
		tst_brkm TFAIL "$RHOSTNAME isn't in rwho output"
	ruptime -a | grep -q $LHOST || \
		tst_brkm TFAIL "$LHOST is not in ruptime outfile"
	ruptime -a | grep -q $RHOSTNAME || \
		tst_brkm TFAIL "$RHOSTNAME is not in ruptime outfile"
}

do_cleanup()
{
	if [ "$LHOST_PID" ]; then
		tst_resm TINFO "Stopping rwhod on $LHOST"
		killall rwhod
	fi

	if [ "$RHOST_PID" ]; then
		tst_resm TINFO "Stopping rwhod on $RHOST"
		tst_rhost_run -c "killall rwhod"
	fi
}

do_setup

for i in $(seq 1 $TST_TOTAL); do
	do_test
	tst_resm TPASS "Test $i/$TST_COUNT complete"
done

tst_exit
