#!/bin/bash
# UEC registration helper script
# Allows to set components registration mode (manual or automatic)

NAME=`basename $0`
LOCK_LOCATION=/var/lib/eucalyptus/registration.lock

usage () {
  echo "$NAME [--manual|--auto|--help]"
  echo
  echo "  Options:"
  echo "     --manual      Disable automatic component registration"
  echo "     --auto        Enable automatic component registration"
  echo "     -h, --help    This message"
}

check_root () {
  if [[ $EUID -ne 0 ]]; then
    echo "To change registration mode, you need to run this command as root."
    echo "You can do so by running 'sudo $NAME $1'"
    exit 1
  fi
}

listener-is-running () {
  if status uec-component-listener 2>&1 | grep "start/running" > /dev/null; then
    return 0
  else
    return 1
  fi
}

if [ $# -gt 1 ]; then
  echo "Error: Only one option allowed."
  usage
  exit 1
fi

if [ $# -eq 1 ]; then
  if [ "$1" = "-h" -o "$1" = "--help" ]; then
    usage
    exit 0
  else
    if [ "$1" = "--manual" ]; then
      REGMODE="manual"
      check_root --manual
    else
      if [ "$1" = "--auto" ]; then
        REGMODE="auto"
        check_root --auto
      else
        echo "Error: option '$1' is invalid"
        usage
        exit 1
      fi
    fi
  fi
fi

if [ -f $LOCK_LOCATION ]; then
  echo "Automatic components registration is disabled on this controller."
  if listener-is-running; then
    echo "However, uec-component-listener is still running."
  else
    REGSTATUS=manual
  fi
else
  echo "Automatic components registration is enabled on this controller."
  if ! listener-is-running; then
    echo "However, uec-component-listener is not running."
  else
    REGSTATUS=auto
  fi
fi

if [ "$REGMODE" = "manual" ]; then
  if [ "$REGSTATUS" = "manual" ]; then
    echo "Registration is already in manual mode."
  else
    echo "Setting UEC registration mode to manual."
    touch $LOCK_LOCATION && stop uec-component-listener
    exit $?
  fi
fi

if [ "$REGMODE" = "auto" ]; then
  if [ "$REGSTATUS" = "auto" ]; then
    echo "Registration is already in auto mode."
  else
    echo "Setting UEC registration mode to auto."
    rm $LOCK_LOCATION && start uec-component-listener
    exit $?
  fi
fi

exit 0
