#!/usr/bin/env ruby

# -------------------------------------------------------------------------- #
# Copyright 2002-2025, OpenNebula Project, OpenNebula Systems                #
#                                                                            #
# Licensed under the Apache License, Version 2.0 (the "License"); you may    #
# not use this file except in compliance with the License. You may obtain    #
# a copy of the License at                                                   #
#                                                                            #
# http://www.apache.org/licenses/LICENSE-2.0                                 #
#                                                                            #
# Unless required by applicable law or agreed to in writing, software        #
# distributed under the License is distributed on an "AS IS" BASIS,          #
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   #
# See the License for the specific language governing permissions and        #
# limitations under the License.                                             #
#--------------------------------------------------------------------------- #

###############################################################################
# This script is used to register a new IP network in the IPAM. The network may
# be selected by a pool of free networks or if an specific network is requested
# its availability maybe checked by the IPAM driver.
#
# The IPAM driver must return an OpenNebula AddressRange definition, potentially
# augmented with network specific variables to be used by VMs (e.g. GATEWAYS,
# MASK...)
#
# STDIN Input:
#   - Base64 encoded XML with AR request
#
# XML format
#  <IPAM_DRIVER_ACTION_DATA>
#    <AR>
#      <SIZE>Number of IPs to allocate</SIZE>
#      <PROVISION_ID>ID</PROVISION_ID>
#    </AR>
#  </IPAM_DRIVER_ACTION_DATA>
#
# The response MUST include IPAM_MAD, TYPE, IP and SIZE attributes, example:
#   - A basic network definition
#       AR = [
#         IPAM_MAD = "ec2",
#         TYPE = "IP4",
#         IP   = "10.0.0.1",
#         SIZE = "255",
#         DEPLOY_ID = "..",
#       ]
#
#   - A complete network definition. Custom attributes (free form, key-value)
#     can be added, named cannot be repeated.
#       AR = [
#         IPAM_MAD = "ec2",
#         TYPE = "IP4",
#         IP   = "10.0.0.2",
#         SIZE = "200",
#         DEPLOY_ID = "..",
#         NETWORK_ADDRESS   = "10.0.0.0",
#         NETWORK_MASK      = "255.255.255.0",
#         GATEWAY           = "10.0.0.1",
#         DNS               = "10.0.0.1",
#         IPAM_ATTR         = "10.0.0.240",
#         OTHER_IPAM_ATTR   = ".mydoamin.com"
#       ]
################################################################################

ONE_LOCATION = ENV['ONE_LOCATION'] unless defined?(ONE_LOCATION)

if !ONE_LOCATION
    LIB_LOCATION      ||= '/usr/lib/one'
    RUBY_LIB_LOCATION ||= '/usr/lib/one/ruby'
    GEMS_LOCATION     ||= '/usr/share/one/gems'
else
    LIB_LOCATION      ||= ONE_LOCATION + '/lib'
    RUBY_LIB_LOCATION ||= ONE_LOCATION + '/lib/ruby'
    GEMS_LOCATION     ||= ONE_LOCATION + '/share/gems'
end

# %%RUBYGEMS_SETUP_BEGIN%%
require 'load_opennebula_paths'
# %%RUBYGEMS_SETUP_END%%

$LOAD_PATH << RUBY_LIB_LOCATION
$LOAD_PATH << LIB_LOCATION + '/oneprovision/lib'

require 'base64'
require 'nokogiri'
require 'aws-sdk-ec2'
require 'opennebula'
require 'oneprovision'
require 'ipaddr'

# Add ^ and < operators to the IPAddr class
class IPAddr

    attr_reader :addr

    def ^(other)
        clone.set(@addr ^ other.to_i)
    end

    def <(other)
        @addr < other.addr
    end

end

begin
    data = Nokogiri::XML(Base64.decode64(STDIN.read))

    # --------------------------------------------------------------------------
    # Get connection details for the provider
    # --------------------------------------------------------------------------
    provision_id = data.xpath('//AR/PROVISION_ID').text

    if provision_id.empty?
        STDERR.puts 'Missing provision id in address range'
        exit(-1)
    end

    one       = OpenNebula::Client.new
    provision = OneProvision::Provision.new_with_id(provision_id, one)
    rc        = provision.info

    if OpenNebula.is_error?(rc)
        STDERR.puts rc.message
        exit(-1)
    end

    aws_conf = provision.body['aws_configuration']

    if aws_conf
        cidr_s = aws_conf['cidr']
    else
        cidr_s = data.xpath('//AR/CIDR').text
    end

    mask = cidr_s.split('/')[1]

    if cidr_s.empty?
        STDERR.puts 'Missing CIDR block in aws_configuration or AR'
        exit(-1)
    end

    cidr = IPAddr.new(cidr_s)

    if !['255.255.0.0', '16'].include? mask
        STDERR.puts 'Elastic CIDR block has to be /16'
        exit(-1)
    end

    provider = provision.provider
    connect  = provider.body['connection']

    options = {
        :access_key_id     => connect['access_key'],
        :secret_access_key => connect['secret_key'],
        :region            => connect['region']
    }

    # --------------------------------------------------------------------------
    # Connect to AWS and allocate a new IP. Model a 2-host network for the
    # public IP.
    #   Gateway = IP ^ 1
    #   IP      = IP/31
    # --------------------------------------------------------------------------
    size = data.xpath('//AR/SIZE').text.to_i

    if size.to_i != 1
        STDERR.puts 'Only address ranges of size 1 are supported'
        exit(-1)
    end

    Aws.config.merge!(options)

    ec2 = Aws::EC2::Resource.new.client
    ip  = ec2.allocate_address({ :domain => 'vpc' })

    eip = IPAddr.new(ip.public_ip)

    ipvm = (eip & 0x0000FFFF) | cidr.mask(16)
    ipgw = ipvm ^ 1

    first_ip = IPAddr.new('0.0.0.16') | cidr.mask(16)

    if ipvm < first_ip
        ec2.release_address({ :allocation_id => ip.allocation_id })

        STDERR.puts 'Could not allocate Elastic IP'
        exit(-1)
    end

    puts <<-EOF
        AR = [
            TYPE = "IP4",
            IP   = "#{ipvm}",
            EXTERNAL_IP = "#{ip.public_ip}",
            SIZE     = "1",
            IPAM_MAD = "aws",
            GATEWAY      = "#{ipgw}",
            NETWORK_MASK = "255.255.255.254",
            AWS_ALLOCATION_ID = "#{ip.allocation_id}",
            PROVISION_ID      = "#{provision_id}"
        ]
    EOF
rescue StandardError => e
    STDERR.puts e.to_s
    exit(-1)
end
