#! /usr/bin/env ruby
#--
# Copyright (c) 2010 Novell, Inc.
# All Rights Reserved.
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of version 2 of the GNU General Public License
# as published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, contact Novell, Inc.
#
# To contact Novell about this file by physical or electronic mail,
# you may find current contact information at www.novell.com
#++
require 'rubygems'
require 'nokogiri'

class Resource
  attr_accessor :type, :title   # String
  attr_accessor :parameters     # Hash

  def initialize(type, title, parameters = {})
    @type, @title, @parameters = type, title, parameters
  end

  def to_s
    parameters_s = parameters.keys.sort.map{|k| "  #{k} => '#{parameters[k]}',\n"}.join ""

    "#{type} { '#{title}':\n#{parameters_s}}\n"
  end
end

puts "# Generated from #{ARGV[0]}"
puts "# on #{Time.now}"
puts "# using kiwi2puppet [URL]"

doc = Nokogiri::XML(File.open(ARGV[0]))

packages = doc.at_xpath "/image/packages[@type='image']"
packages.xpath('package').each do |p|
  # http://docs.puppetlabs.com/guides/types/package.html
  r = Resource.new "package", p["name"], "ensure" => "present"
  print r
end
# 'warning: Found multiple default providers for package: gem, rpm; using gem'
puts "# do not prefer gem"
puts "Package { provider => 'rpm' }"

doc.xpath("/image/repository/source").each do |repo|
  # http://docs.puppetlabs.com/guides/types/yumrepo.html
  repo_r = Resource.new "yumrepo", repo["path"], "baseurl" => repo["path"]
  print repo_r
end

# TODO TEST: get some complete kiwi profile,
# this is only from a Studio export
doc.xpath("/image/users").each do |group| # really, users==group
  # http://docs.puppetlabs.com/guides/types/group.html
  group_r = Resource.new "group", group["group"]
  print group_r
  group.xpath("user").each do |user|
    # http://docs.puppetlabs.com/guides/types/user.html
    user_r = Resource.new "user", user["name"], {
      "shell" => user["shell"],
      "password" => user["pwd"],
      "gid" => group_r.title
    }
    print user_r
  end
end
