#!/bin/bash -x
# script to copy relevent information to the vpn server
# scriptname:cloud

# Make sure only root can run our script
if [ "$(id -u)" != "0" ]; then
    echo "This script must be run as root. Please type 'su' and issue command again." 1>&2
    exit 1
fi


VPNSERVER=5.5.0.1
if [ -f /root/deployment ];then
  DEPLOYNAME=`cat /root/deployment`
else
  echo "this script needs a unique deployment name in /root/deployment. Quiting"
  exit 1
fi

function skip_ifrecent {
RECENT_CHECK='-daystart -mtime 0' 
if [ `find /root/site/$DEPLOYNAME/xfer-done.txt $RECENT_CHECK 2>/dev/null` ];then
exit 0
fi
}

function skip_ifoffline {
# a vpn connection can take a while to come up
  for i in `seq 1 10`;do
    ping -c 3 -w 3 $VPNSERVER
    if [ $? -eq 0 ]; then
       return
    fi
    sleep 10 
  done
  echo
  echo "giving up on starting the VPN connection, "
  exit 1
}

function cpy_pwrlogs_ifxo {
if [ -f /proc/device-tree/mfg-data/MN ]; then
    rsync -rp -e "ssh -i /root/.ssh/remote_site" /home/olpc/power-logs site@5.5.0.1:/home/site/$DEPLOYNAME
    acpower -d -p > /root/site/$DEPLOYNAME/acpower.txt
fi
}

mkdir -p /root/site/$DEPLOYNAME

# bring up the vpn connection if it's not up
vpnstart

skip_ifoffline
#skip_ifrecent

cpy_pwrlogs_ifxo

# copy data that should be uploaded to $DEPLOYNAME
date > /root/site/$DEPLOYNAME/last_update.txt
rsync -rp -e "ssh -i /root/.ssh/remote_site" /root/site/$DEPLOYNAME/* site@5.5.0.1:/home/site/$DEPLOYNAME/

touch /root/site/$DEPLOYNAME/xfer-done.txt
