#!/bin/bash
if [ ! -f "$1" ]; then
  echo "error: must supply rooms list"
  exit 1
fi

if [ -z "$2" ]; then
  ./mkhosts.sh "$1"
  ./mkacatcher_cpp.sh "$1"
fi

if [ ! -z "$2" ]; then
  if grep -q "$2" "$1" ]; then
    HOSTS="$2"
  fi
else
  HOSTS="`cat $1`"
fi
echo $HOSTS
for HOST in $HOSTS; do
  >&2 echo "provisioning host $HOST"
  ssh pi@$HOST "if [ ! -d \$HOME/.ssh ]; then mkdir \$HOME/.ssh; fi; echo `cat $HOME/.ssh/id_rsa.pub` >> \$HOME/.ssh/authorized_keys; chmod 700 \$HOME/.ssh; chmod 644 \$HOME/.ssh/authorized_keys"
  for FILE in HOSTS SERVERIP stream.sh set_hostname.sh v4lcap.c; do scp -p $FILE pi@$HOST:$FILE; done
  ssh pi@$HOST "if ! dpkg -s screen >/dev/null 2>&1 ; then sudo apt-get -y install screen; else echo "screen already installed." ; fi"
  ssh pi@$HOST "if [ -f v4lcap -a v4lcap -nt v4lcap.c ]; then echo v4lcap already current; else make v4lcap; fi"
  ssh pi@$HOST "cd \$HOME && bash set_hostname.sh"
  #ssh pi@$HOST "sudo reboot"
done

echo "all machines provisioned."
#echo "all machines will require a few minutes to reboot, be patient grasshopper"
