#!/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.                                             #
# -------------------------------------------------------------------------- #

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

#-------------------------------------------------------------------------------
#
#-------------------------------------------------------------------------------
class LinuxContainersMarket

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

    TEMPLATE = "
CPU = \"1\"
MEMORY = \"768\"
LXD_SECURITY_PRIVILEGED = \"true\"
GRAPHICS = [
    LISTEN  =\"0.0.0.0\",
    TYPE  =\"vnc\"
]
CONTEXT = [
    NETWORK  =\"YES\",
    SSH_PUBLIC_KEY  =\"$USER[SSH_PUBLIC_KEY]\",
    SET_HOSTNAME  =\"$NAME\"
    ]"

    #---------------------------------------------------------------------------
    # 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'
        @options[:agent] = "OpenNebula #{File.read(version_path)}" if File.exist? version_path
    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') do |http|
            http.request(req)
        end

        return 0, response.body if response.is_a? Net::HTTPSuccess

        puts response.code.to_i
        puts response.msg
        [response.code.to_i, response.msg]
    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(%r{a href="([a-z].*/)">})
        tree    = {}

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

            next if rc != 0

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

            version_path = {}
            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(%r{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 do |distro, value|
            value.each do |version, path|
                source = app_url(path)
                description = 'Downloaded from https://images.linuxcontainers.org'
                name = "#{distro[0...-1]}_#{version[0...-1]} - LXD"

                data = {
                    'NAME' => name, 'SOURCE' => source.to_s, 'FORMAT' => 'raw',
                    'IMPORT_ID' => '-1', 'ORIGIN_ID' => '-1', 'TYPE' => 'IMAGE',
                    'PUBLISHER' => 'linuxcontainers.org', 'VERSION' => '1.0',
                    'DESCRIPTION' => description, 'REGTIME' => app_time(path),
                    'TAGS' => '', 'SIZE' => @options[:sizemb]
                }

                tmpl = ''

                data.each {|key, value| print_var(tmpl, key, value) }

                tmpl64 = ''
                print_var(tmpl64, 'DRIVER', 'raw')
                print_var(tmpl, 'APPTEMPLATE64', Base64.strict_encode64(tmpl64))
                print_var(tmpl, 'VMTEMPLATE64', Base64.strict_encode64(TEMPLATE))

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

        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

    # Returns build date based on image path
    def app_time(path)
        m1 = 'amd64/default/./'
        m2 = '/rootfs.tar.xz'

        buildate = path[/#{m1}(.*?)#{m2}/m, 1]
        buildate = DateTime.strptime(buildate, '%Y%m%d_%H:%M')
        buildate.to_time.to_i
    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

    pre = 'MARKETPLACE/TEMPLATE'

    data = { :url => "#{pre}/ENDPOINT", :sizemb => "#{pre}/IMAGE_SIZE_MB",
             :fs => "#{pre}/FILESYSTEM", :format => "#{pre}/FORMAT" }

    data.each {|key, value| set_option(options, doc, key, value) }

    puts LinuxContainersMarket.new(options).get_appliances
rescue Exception
end
