#!/bin/sh
#
# Mega simple wrapper for batch control on nodes.
#
# Rick van der Zwet <rick@wirelessleiden.nl>
#

HOSTS=${*:-"`$(dirname $0)/gformat.py list up systems fqdn`"}
PREFIX=${PREFIX:-'ip'}
CMD=${CMD:-'md5 /usr/local/etc/rc.d/lvrouted'}

echo "# WARN: Going to run at: " $HOSTS; sleep 2

cat << 'EOF' >/tmp/command
sh -c ". /etc/rc.subr; load_rc_config "networking"; set" > /tmp/networking-env
grep -e ^ifconfig -e ^ipv4 /tmp/networking-env
{ grep -e ^ipv4 /tmp/networking-env | cut -d= -f2 | tr -d \' | xargs -n1 | cut -d/ -f1;
  grep -e ^ifconfig /tmp/networking-env | grep -v -i 'dhcp' | cut -d= -f2 | tr -d \' | cut -d' ' -f2 | cut -d'/' -f1
} | sort -u > /tmp/current
ifconfig -a | grep 'inet ' | cut -d' ' -f2 | sort > /tmp/config
echo "# Comparing IP differences /tmp/current vs /tmp/config"
sdiff /tmp/current /tmp/config
EOF

# Cleanup old entries
rm $PREFIX-* stderr-*

for HOST in $HOSTS; do
  stdout_file="$PREFIX-${HOST%%.}.txt"
  stderr_file="stderr-${HOST%%.}.txt"
  : > $stdout_file
  : > $stderr_file
  cat /tmp/command | ssh -o ConnectTimeout=3 -o BatchMode=yes root@$HOST 'cat >/tmp/command && sh /tmp/command' 1>$stdout_file 2>$stderr_file &
done

echo "# Wait for all processes to complete."
wait
