#!/bin/sh
prog=netconsole-server
#
# initialize the netconsole using reasonable defaults (normally just the
# client IP address, and possibly the port.  We can determine the MAC
# address of the client system, IP address, the correct device, and verify
# that we are using an ethernet interface (required for netconsole to work).
#
# Andreas Dilger <adilger@turbolinux.com>  Sep 26, 2001

usage()
{
	cat - <<- EOF 1>&2

	Initialize a network message console over UDP.

	usage: $prog [-b] [-d dev] [-m mac] [-p port] target[:port]
		-b       - use broadcast ethernet MAC address
		-m       - specify remote system MAC address (default: detect)
		-p       - local port to use for message traffic (default: 6666)
		-d       - ethernet device to use for messages (default: detect)
		target   - hostname/IP address of remote netconsole-client
		:port    - port on target netconsole-client (default: like -p)
	EOF
	exit 1
}

PATH=$PATH:/sbin:/usr/sbin
PORT=6666

while [ $# -ge 1 ]; do case $1 in
	-b) NOMAC=1 ;;
	-d) DEV=$2; shift ;;
	-m) MAC=$2; shift ;;
	-p) PORT=$2; shift ;;
	*:*) TGT=`echo $1 | sed "s/:.*//"`; TPORT=`echo $1 | sed "s/.*://"` ;;
	*) TGT=$1 ;;
	esac
	shift
done

[ -z "$TGT" ] && usage
[ -z "$TPORT" ] && TPORT=$PORT

ping -c 1 $TGT > /dev/null 2>&1
[ $? -ne 0 ] && echo "$prog: can't ping $TGT" 1>&2 && usage

dquad_to_hex()
{
	echo $1 | sed -e "s/[()]//g" -e "s/\./ /g" | while read I0 I1 I2 I3 ; do
		printf "0x%02X%02X%02X%02X" $I0 $I1 $I2 $I3
	done
}

# output from arp -a of the form:
# good: host.domain (A.B.C.D) at 00:50:BF:06:48:C1 [ether] on eth0
# bad:  ? (A.B.C.D) at <incomplete> on eth0
arp -a | grep $TGT | { read HOSTNAME IPADDR AT MACADDR TYPE ON IFACE;
	[ "$HOSTNAME" = "?" -a -z "$MAC" -a -z "$NOMAC" ] && \
		echo "$prog: can't resolve $TGT MAC" 1>&2 && usage

	[ -z "$MAC" ] && MAC=$MACADDR
	[ -z "$DEV" ] && DEV=$IFACE
	[ "$DEV" = "$IFACE" -a "$TYPE" != "[ether]" ] && \
		echo "$prog: $DEV must be an ethernet interface" 1>&2 && usage
		
	IPHEX=`dquad_to_hex $IPADDR`
	echo $MAC | sed "s/:/ /g" | { read M0 M1 M2 M3 M4 M5;
		if [ -z "$NOMAC" ]; then
			TGTMAC="target_eth_byte0=0x$M0 target_eth_byte1=0x$M1 \
				target_eth_byte2=0x$M2 target_eth_byte3=0x$M3 \
				target_eth_byte4=0x$M4 target_eth_byte5=0x$M5"
		fi
		echo dev=$DEV target_ip=$IPHEX \
			source_port=$PORT target_port=$TPORT $TGTMAC
		/sbin/insmod netconsole dev=$DEV target_ip=$IPHEX \
			source_port=$PORT target_port=$TPORT $TGTMAC
	}
}

