#!/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 unregister a new IP network in the IPAM.
#
# STDIN input:
#   - Base64 encoded XML with AR request
#
# XML format
#  <IPAM_DRIVER_ACTION_DATA>
#    <AR>
#      <DEPLOY_ID>Packet AR ID</DEPLOY_ID>
#      <PACKET_TOKEN>Packet auth token</PACKET_TOKEN>
#    </AR>
#  </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

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

def find_packet_ip_assignment(packet_client, id, cidr)
    packet_client.get_ip(id).assignments.each do |a|
        assignment_id = a['href'].split('/')[-1]

        begin
            packet_ip = packet_client.get_ip(assignment_id)
        rescue StandardError
            next
        end

        packet_cidr = "#{packet_ip.network}/#{packet_ip.cidr}"

        if packet_cidr == cidr
            return packet_ip
        end
    end

    nil
end

###

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

begin
    ipam_state_dir = IPAM_STATE_LOCATION + "/packet/#{ar_deploy_id}"
    ipam_state_f = ipam_state_dir + '/' + ar_ip

    if File.exist? ipam_state_f
        File.unlink(ipam_state_f)
    end

    # check if IP is assigned to any host, unassign
    cidr = ar_ip + '/32'
    packet_ip = find_packet_ip_assignment(packet, ar_deploy_id, cidr)
    packet.delete_ip(packet_ip) if packet_ip
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
