#!/bin/bash
#
# aws-eip - Ensures Assiend Elastic ip 
#
# chkconfig: - 79 21
#
# description: Assign Elastic Ip

### BEGIN INIT INFO
# Required-Start: $network $syslog
# Required-Stop: $network $syslog
# Default-Start:
# Default-Stop:
# Description: Assign Elastic Ip
# Short-Description: Assign Elastic Ip
### END INIT INFO

# Source function library
. /etc/rc.d/init.d/functions

# Source networking configuration
[ -r /etc/sysconfig/network ] && . /etc/sysconfig/network

# Source AWS environment variables
. /etc/profile.d/aws-apitools-common.sh

# Check that networking is configured
if [ "${NETWORKING}" = "no" ]; then
  echo "Networking is not configured."
  exit 1
fi

# Verify Amazon EC2 API Tools
test -d "$AWS_PATH/bin" || {
  echo "ec2-api-tools not installed.";
  if [ "$1" = "stop" ]; then
    exit 0;
  else
    exit 5;
  fi;
}

# Verify curl utility
test -x "$(which curl)" || {
  echo "curl not installed.";
  if [ "$1" = "stop" ]; then
    exit 0;
  else
    exit 5;
  fi;
}


assign_ip() {
  declare -r aws_ip=${1}
  if [ -z "${aws_ip}" ]
  then
    exit 5;
  fi
  aws-ec2-assign-elastic-ip --valid-ips $aws_ip
}

start() {
  declare -rA user_data=$(curl -s http://169.254.169.254/latest/user-data)
  assign_ip ${user_data["elastic-ip"]}
}

stop() {
  echo "Nothing to do here"
}
 
restart() {
  stop
  start
}
 
# See how we were called.
case "$1" in
  start)
    start
    ;;
  stop)
    stop
    ;;
  restart)
    restart
    ;;
  *)
    echo $"Usage: $0 {start|stop|restart}"
    exit 1
esac
 
exit $?
