#!/usr/bin/env ruby

# -------------------------------------------------------------------------- #
# Copyright 2002-2018, 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.                                             #
# -------------------------------------------------------------------------- #

require 'net/http'
require 'uri'
require 'json'
require 'base64'
require 'rexml/document'

#-------------------------------------------------------------------------------
#
#-------------------------------------------------------------------------------
class LinuxContainersMarket
    #---------------------------------------------------------------------------
    # Default Configuration parameters for the Driver
    #---------------------------------------------------------------------------
    DEFAULTS = {
        :url    => 'https://images.linuxcontainers.org',
        :sizemb => 5120,
        :fs     => 'ext4',
        :format => 'raw',
        :agent  => 'OpenNebula'
    }

    #---------------------------------------------------------------------------
    # Configuration varibales
    #   :url of linuxcontainers market place
    #   :sizemb default size for container images
    #   :fs filesystem for the image file
    #   :format for the image file, qcow2, raw
    #   :agent for HTTP client
    #---------------------------------------------------------------------------
    def initialize(options = {})
        @options = DEFAULTS
        @options.merge!(options)

        version_path = File.dirname(__FILE__) + '/../../VERSION'

        if File.exists? version_path
            @options[:agent] = "OpenNebula #{File.read(version_path)}"
        end
    end

    # Get container information
    def get(path)
        # Get proxy params (needed for ruby 1.9.3)
        http_proxy = ENV['http_proxy'] || ENV['HTTP_PROXY']

        if http_proxy
            p_uri   = URI(http_proxy)
            p_host  = p_uri.host
            p_port  = p_uri.port
        else
            p_host  = nil
            p_port  = nil
        end

        uri = URI(@options[:url] + path)

        rc  = Net::HTTP.get_response(uri)

        uri = URI(rc['location']) if rc.is_a? Net::HTTPRedirection

        req = Net::HTTP::Get.new(uri.request_uri)

        req['User-Agent'] = @options[:agent]

        response = Net::HTTP.start(uri.hostname, uri.port, p_host, p_port,
            :use_ssl => uri.scheme == 'https') { |http|
            http.request(req)
        }

        if response.is_a? Net::HTTPSuccess
            return 0, response.body
        else
            puts response.code.to_i
            puts response.msg
            return response.code.to_i, response.msg
        end
    end

    # Get the list of appliances
    def get_appliances()
        first_level = '/images/'

        rc, body = get(first_level)

        return rc, body if rc != 0

        distros = body.scan(/a href="([a-z].*\/)">/)
        tree    = Hash.new

        distros.each do |distro|
            rc, body = get(first_level + distro[0])

            next if rc != 0

            version = body.scan(/a href="(.*\/)">/)
            version.shift #Remove first entry ("Parent Directory")

            version_path = Hash.new
            version.each do |version|
                path   = "#{first_level}#{distro[0]}#{version[0]}amd64/default/"
                rc, body = get(path)

                next if rc != 0

                release_dates = body.scan(/a href="(.*\/)">/)

                #Previous release_dates array leaves a point in the html page
                release_date  = release_dates.last[0]
                version_path[version[0]] = "#{path}#{release_date}rootfs.tar.xz"
            end

            tree[distro[0]] = version_path
        end

        appstr  = ""

        #-----------------------------------------------------------------------
        # Generate the container app information
        #-----------------------------------------------------------------------
        tree.each { |distro, value|
            value.each { |version, path|

            id     = "-1"
            source = app_url(path)

            description = "Downloaded from https://images.linuxcontainers.org"

            tmpl = ""

            print_var(tmpl, "NAME", "#{distro[0...-1]}_#{version[0...-1]}")
            print_var(tmpl, "SOURCE", "#{source}")
            print_var(tmpl, "IMPORT_ID", id)
            print_var(tmpl, "ORIGIN_ID", "-1")
            print_var(tmpl, "TYPE", "IMAGE")
            print_var(tmpl, "PUBLISHER", "linuxcontainers.org")
            print_var(tmpl, "FORMAT", "raw")
            print_var(tmpl, "DESCRIPTION", description)
            print_var(tmpl, "VERSION", "1.0")
            print_var(tmpl, "TAGS", "")
            print_var(tmpl, "REGTIME", "1523362012")
            print_var(tmpl, "SIZE", @options[:sizemb])

            tmpl64 = ""
            print_var(tmpl64, "DRIVER", "raw")
            print_var(tmpl, "APPTEMPLATE64", Base64::strict_encode64(tmpl64))

            appstr << "APP=\"#{Base64::strict_encode64(tmpl)}\"\n"
            }
        }

        appstr
    end

    private

    # Generate the URL for the appliance
    #   path of the continer at linuxcontainers.org
    # Example:
    #
    # lxd://https://images.linuxcontainers.org/images/ubuntu/xenial/amd64/default/\
    #    ./20181214_07:42/rootfs.tar.xz?size=5120&filesystem=ext4&format=raw
    #
    def app_url(path)
        "\\\"lxd://#{@options[:url]}#{path}?size=#{@options[:sizemb]}&filesystem=" \
            "#{@options[:fs]}&format=#{@options[:format]}\\\""
    end

    # Print variable in an APP template
    def print_var(str, name, val)
        return if val.nil?
        return if val.class == String && val.empty?

        str << "#{name}=\"#{val}\"\n"
    end
end

################################################################################
# Main Program. Outpust the list of marketplace appliances
################################################################################
def set_option(o, d, name, path)
    o[name] = d.elements[path].text if d.elements[path]
end

begin
    options     = {}
    drv_message = Base64::decode64(ARGV[0])

    doc = REXML::Document.new(drv_message).root

    set_option(options, doc, :url, 'MARKETPLACE/TEMPLATE/ENDPOINT')
    set_option(options, doc, :sizemb, 'MARKETPLACE/TEMPLATE/IMAGE_SIZE_MB')
    set_option(options, doc, :fs, 'MARKETPLACE/TEMPLATE/FILESYSTEM')
    set_option(options, doc, :format, 'MARKETPLACE/TEMPLATE/FORMAT')

    puts LinuxContainersMarket.new(options).get_appliances

rescue Exception
end

