#!/usr/bin/env ruby

require 'fileutils'
require 'yaml'
require 'find'

APAKA_RELEASE_INSTALL_DIR = "/opt/rock/master-20.06"
APAKA_PKG_INSTALL_DIR = "/opt/rock/master-20.06/rock-master-20.06-base-templates-ruby-lib"
APAKA_RELEASE_DOC_INSTALL_DIR = "#{APAKA_RELEASE_INSTALL_DIR}/share/doc"

def update_index_html(remove: false)
    apaka_doc_dir = Dir.glob(File.join(APAKA_RELEASE_INSTALL_DIR,"*","share","[a-zA-Z]*"))

    # make sure release doc directory exists
    FileUtils.mkdir_p APAKA_RELEASE_DOC_INSTALL_DIR unless File.exist?(APAKA_RELEASE_DOC_INSTALL_DIR)

    packages_indexes = {}
    # collect candidate files in the directories
    apaka_doc_dir.each do |doc_dir|
        pkg_name = $1
        if doc_dir =~ /\/([^\/]+)\/share/
            pkg_name = $1
        else
            next
        end

        Find.find(doc_dir) do |path|
            if path =~ /\/index.htm/
                packages_indexes[pkg_name] ||= []
                packages_indexes[pkg_name] << path
            end
        end
    end
    create_index_html(packages_indexes, remove: remove)
end

def create_index_html(index_list, remove: false)
    html = <<-END
<html>
<head>
<title>Rock package documentation index</title>
</head>
<body>
<h1>Rock package documentation index</h1>
<ul>
END
    added_packages = []
    sorted_packages = index_list.keys.sort
    sorted_packages.each do |pkg|
        pkg_indexes = index_list[pkg]
        pkg_indexes.each_with_index do |path, idx|
            pkg_link_name = pkg

            doc_pkg_link = File.join(APAKA_RELEASE_INSTALL_DIR, "share","doc",pkg_link_name)
            FileUtils.rm doc_pkg_link if File.symlink?(doc_pkg_link)

            if remove && APAKA_PKG_INSTALL_DIR =~ /#{pkg}$/
                next
            end

            pkg_dir = File.join(APAKA_RELEASE_INSTALL_DIR, pkg)
            Dir.chdir(APAKA_RELEASE_DOC_INSTALL_DIR) do 
                cmd = "ln -rs #{pkg_dir} #{pkg_link_name}"
                if !system(cmd)
                    puts "postinst for #{pkg}: Failed to link with: #{cmd}"
                end
            end

            if path =~ /(share\/.*)/
                relative_path_pkg_index = $1
                if idx > 0
                    pkg_link_name += "_#{idx}"
                end

                html_list_item = <<-END
<li><a href="#{File.join(pkg,relative_path_pkg_index)}">#{pkg_link_name}</a>
END
                html += html_list_item
            end
            added_packages << pkg
        end
    end
    html_end = <<-END
</ul>
</body>
</html>
END
    html += html_end
    
    index_file = File.join(APAKA_RELEASE_DOC_INSTALL_DIR,"index.html")
    if added_packages.empty?
        FileUtils.rm index_file if File.exist?(index_file)
    else
        File.open(index_file,"w") do |file|
            file.write(html)
        end
    end
end

# Update the env.yml file with the information provided in the env.yml
# file
def update_env_yml
    append_file = File.join(APAKA_PKG_INSTALL_DIR, "env.yml.append")
    return unless File.exist?(append_file)

    env_file = File.join(APAKA_PKG_INSTALL_DIR,"env.yml")
    env_data = YAML.load_file(env_file) || {}

    File.open(append_file).each_line do |line|
        variable, value = line.strip.split(" ")
        if env_data.include?(variable)
            env_data[variable][:values] << value.strip
        else
            env_data[variable] = { 
                :type => :add,
                :values => [ value.strip ] 
            }
        end
        env_data[variable][:values].uniq!
    end
    File.open(env_file,"w") do |file|
        file.write(env_data.to_yaml)
    end

    FileUtils.rm(append_file)
end

cmd = ARGV.shift
if $0 =~ /postinst$/ 
    return unless cmd

    case cmd
    when "configure"
	#called when the package files have been installed during installation
	#of the package
	update_index_html()
        update_env_yml()
    when "abort-upgrade"
        #called during package upgrade/install
    when "abort-remove"
        #called during package upgrade/install
    when "abort-deconfigure"
        #called during package upgrade/install
    end
elsif $0 =~ /postrm$/
    return unless cmd

    case cmd
    when "remove"
        #called after removal of the packages files during removal of the
        #package
        update_index_html(remove: true)
    when "purge"
        #called after "remove"
    when "upgrade"
        #called during package upgrade/install
    when "disappear"
        #called during package upgrade/install
    when "failed-upgrade"
        #called during package upgrade/install
    when "abort-install"
        #called during package upgrade/install
    when "abort-upgrade"
        #called during package upgrade/install
    end
end
