#!/bin/bash

# Storage controller registration script
# Registers SC at IP $2 with cluster $1 (on CLC)

# Source common functions
. /usr/share/eucalyptus/registration/common

# Parameter sanitizing
CLUSTERNAME=${1% storage}
IP=$2
testip "${IP}"

# Check if SC isn't already registered
for sc in `euca_conf --list-scs | tail -n +2 | awk '{ print $1 }'`; do
  if [ "$sc" == "$CLUSTERNAME" ]; then
    reglog "SC for $CLUSTERNAME is already registered."
    exit 1
  fi
done

# Register SC if CC exists
function tryregistersc {
  for cc in `euca_conf --list-clusters | tail -n +2 | awk '{ print $1 }'`; do
    if [ "$cc" == "$1" ]; then
      SHORT_COMMAND="euca_conf --register-sc"
      REAL_COMMAND="/usr/sbin/euca_conf --no-rsync --skip-scp-hostcheck --register-sc "${CLUSTERNAME}" "${IP}""
      COMMAND_OUTPUT=$(eval $REAL_COMMAND)
      STATUS=$?
      if [ $STATUS -eq 0 ];then
        reglog "$SHORT_COMMAND returned SUCCESS"
      else
        reglog "$SHORT_COMMAND returned FAILURE (error $STATUS): Command attempted was \"$REAL_COMMAND\", and had the following output: \"$COMMAND_OUTPUT\""
      fi
      exit 0
    fi
  done
}

tryregistersc "${CLUSTERNAME}"

retries=2
while [ $retries -gt 0 ]; do
  reglog "Cluster $CLUSTERNAME doesn't exist, retrying in 10 seconds."
  sleep 10
  tryregistersc "${CLUSTERNAME}"
  tries=$(($tries-1))
done

reglog "Cluster $CLUSTERNAME doesn't exist"
exit 1
