#!/bin/sh
#
# Upload image to the 'distribution' server. First try WL network, 
# else use inet as last resort. Need to have shell access to distribution server.
#
# XXX: Needs Type and such as well properly
#
# Rick van der Zwet <info@rickvanderzwet.nl>

SERVERS="sunfire.wleiden.net sunfire.wirelessleiden.nl"
TIMESTAMP=`date "+%Y%m%d-%H%M"`
BASEDIR=`dirname $0`
SSH_USER=${SSH_USER:-$USER}
TYPE="$1"
RELEASE="$2"

. $BASEDIR/common.inc.sh

if [ -z "$RELEASE" ]; then
  echo "Usage: $0 <full|image> <release_name>"
  exit 1
fi

# Make sure we find the right image
if [ "$TYPE" = "full" ]; then
  find_disk_full ""
elif [ "$TYPE" = "image" ]; then
  find_disk_image ""
else
  echo "Usage: $0 <full|image> <release_name>"
  exit 1
fi

check_reachable() {
  ping -c 2 -t 1 -q $1 1>/dev/null 2>/dev/null
  return $?
} 

# XXX: Hack this should actually be done during building phase
echo "# Compressing image '$IMG'" 
gzip -v -k -f $IMG
IMG="$IMG.gz"

echo "# Trying to upload to server, alarm messages are normal"
# Upload the image to the defined place
for SERVER in $SERVERS; do
  if check_reachable $SERVER; then
    TARGET="$SSH_USER@$SERVER:/usr/local/www/images/$RELEASE/node-$TYPE-$TIMESTAMP.img.gz"
    echo "# Source: $IMG"
    echo "# Target: $TARGET"
    echo "# To cancel, please CTRL+C within 3 seconds"
    sleep 3
    scp $IMG $TARGET
    exit $?
  fi
done

