#!/usr/bin/env ruby

# -------------------------------------------------------------------------- #
# Copyright 2002-2019, 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 an IP address as used. The IP will be used
# by an OpenNebula VM and should not be allocated to any other host in the
# network.
#
# This scripts MUST exit 0 if the address is free.
#
# STDIN input:
#   - Base64 encoded XML with the AR description and the address request
#
# XML format
#  <IPAM_DRIVER_ACTION_DATA>
#    <AR>
#      <DEPLOY_ID>Packet AR ID</DEPLOY_ID>
#      <PACKET_TOKEN>Packet auth token</PACKET_TOKEN>
#    </AR>
#    <ADDRESS>
#      <IP>IP to allocate</IP>
#    </ADDRESS>
#  </IPAM_DRIVER_ACTION_DATA>
################################################################################

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

if !ONE_LOCATION
    PACKET_LOCATION     = '/usr/lib/one/ruby/vendors/packethost/lib'
    IPAM_STATE_LOCATION = '/var/lib/one/ipam_state'
    RUBY_LIB_LOCATION   = '/usr/lib/one/ruby'
    GEMS_LOCATION       = '/usr/share/one/gems'
else
    PACKET_LOCATION     = ONE_LOCATION + '/lib/ruby/vendors/packethost/lib'
    IPAM_STATE_LOCATION = ONE_LOCATION + '/var/ipam_state'
    RUBY_LIB_LOCATION   = ONE_LOCATION + '/lib/ruby'
    GEMS_LOCATION       = ONE_LOCATION + '/share/gems'
end

if File.directory?(GEMS_LOCATION)
    Gem.use_paths(GEMS_LOCATION)
end

$LOAD_PATH << PACKET_LOCATION
$LOAD_PATH << RUBY_LIB_LOCATION

# gem 'packethost', '> 0.0.8'

require 'packet'
require 'base64'
require 'nokogiri'
require 'fileutils'
require 'opennebula'

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

###

ar_token = data.xpath('//AR/PACKET_TOKEN').text
ar_deploy_id = data.xpath('//AR/DEPLOY_ID').text.to_s
ar_ip = data.xpath('//ADDRESS/IP').text
ar_size = data.xpath('//ADDRESS/SIZE').text

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

packet = Packet::Client.new
packet.auth_token = ar_token

# initialize IPAM state dirs
ipam_state_dir = IPAM_STATE_LOCATION + "/packet/#{ar_deploy_id}"
FileUtils.mkdir_p(ipam_state_dir)

begin
    packet_ip = packet.get_ip(ar_deploy_id)

    cidrs = packet.available_cidr(packet_ip, '32')

    ipam_state_f = ipam_state_dir + '/' + ar_ip

    if !File.exist?(ipam_state_f) && cidrs.include?("#{ar_ip}/32")
        File.new(ipam_state_f, 'w')
        exit(0)
    else
        exit(-1)
    end
rescue StandardError => e
    error_str = "ERROR MESSAGE --8<------\n"
    error_str << e.to_s
    error_str << "\nERROR MESSAGE ------>8--"

    STDERR.puts error_str
    exit(-1)
end
