#!/usr/bin/env python3
#-*- coding: utf-8 -*-
""" OpenNebula ALLOCATE ADDRESS """

# Standard library imports
from base64 import b64decode
from datetime import datetime
from random import randint
from sys import argv, stdin

# Third party library imports
from xmltodict import parse

# Variables
ACTION = 'ALLOCATE'
LOG_FILE = open('/var/log/one/ipam_efs.log', 'a')
REQ_ID = randint(1, 1000)
VERBOSE = True

###############################################################################
# This script is used to set an IP address as free. The IP will be released
# by OpenNebula VMs
#
# This scripts MUST exit 0 if the address is freed.
#
# Input Arguments:
#  $1 - Base64 encoded XML with the AR description and the address request
#  $2 - Request ID
#
# XML format
#  <IPAM_DRIVER_ACTION_DATA>
#  <AR>
#    <TYPE>IP4</TYPE>
#    <IP> First IP in the network in '.' notation
#    <MAC> First MAC in the network in ':' notation
#    <SIZE>Number of IPs in the network
#    <NETWORK_ADDRESS> Base network address
#    <NETWORK_MASK> Network mask
#    <GATEWAY> Default gateway for the network
#    <DNS> DNS servers, a space separated list of servers
#    <GUEST_MTU> Sets the MTU for the NICs in this network
#    <SEARCH_DOMAIN> for DNS client
# <ADDRESS>
#   <IP>
#   <SIZE> Number of IPs to allocate
#   <MAC> MAC is optional
#
################################################################################

def get_args(DRV_ACTION):
    """ Decode args """
    xml_args = b64decode(DRV_ACTION)
    return parse(xml_args)['IPAM_DRIVER_ACTION_DATA']

def log_me(string, force=False):
    """ Format log """
    if VERBOSE or force:
        LOG_FILE.write('%s [%s]: [%s] %s\n' % (
            datetime.now().strftime("%F %T"),
            REQ_ID,
            ACTION,
            string))

def main():
    """ Main class """
    DRV_ACTION = ''
    for l in stdin:
        DRV_ACTION += l
    log_me('base64 args: {}'.format(DRV_ACTION))
    args = get_args(DRV_ACTION)
    log_me('get_args : %s' % args)

main()

log_me('Done.')
LOG_FILE.close()

exit(0)

