#!/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

##
## Network differences
##
#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/config
#ifconfig -a | grep 'inet ' | cut -d' ' -f2 | sort > /tmp/current
#echo "# Comparing IP differences /tmp/current vs /tmp/config"
#diff -u /tmp/current /tmp/config
#EOF

##
## Migrate SSH authorized_keys symlink to new location.
##
#cat <<'EOF' > /tmp/command
#mount -uwo noatime / && unlink /root/.ssh &&  mkdir /root/.ssh && ln -s /etc/ssh/authorized_keys /root/.ssh/ && mount -ur 
#EOF

##
## View lvrouted configured flages
##
#/usr/local/etc/rc.d/lvrouted rcvar | grep flags

#
# Sync lvrouted and wl-config files
#
cat <<'EOF' > /tmp/command
mount -uwo noatime / || exit 1
trap "mount -ur /; exit 1" 1 2 3 15
trap "mount -ur /; exit 0" 0

cp -v /tmp/wl-config /tools || exit 1
cp -v /tmp/lvrouted.in /usr/local/etc/rc.d/lvrouted || exit 1
cp -v /tmp/lvrouted.in /conf/base/etc/local/rc.d/lvrouted || exit 1
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
  {
    scp -o ConnectTimeout=3 -o BatchMode=yes /tmp/wl-config /tmp/lvrouted.in root@$HOST:/tmp
    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
