#!/usr/bin/env ruby

require "rexml/document"
require "ftools"
include REXML
INKSCAPE = '/usr/bin/inkscape'
SRC = "./svg"

def renderit(file)
  svg = Document.new(File.new("#{SRC}/#{file}", 'r'))
  context = svg.root.elements['//dc:description'].text
  svg.root.each_element("//g[@inkscape:label='plate']/rect") do |icon|
    dir = "#{icon.attributes['width']}x#{icon.attributes['height']}/#{context}"
    cmd = "#{INKSCAPE} -i #{icon.attributes['id']} -e #{dir}/#{file.gsub(/\.svg$/,'.png')} #{SRC}/#{file} > /dev/null 2>&1"
    File.makedirs(dir) unless File.exists?(dir)
    system(cmd)
    print "."
    #puts cmd
  end
end

def expungeit(file)
  svg = Document.new(File.new("#{SRC}/#{file}"), 'r')
  context = svg.root.elements['//dc:description'].text
  plate = svg.root.elements["//g[@inkscape:label='plate']/rect[@inkscape:label='scalable']"]
  x = plate.attributes['x']
  y = plate.attributes['y']
  artwork = svg.root.elements["//g[@inkscape:label='artwork']/g[@inkscape:label='scalable']"]
  translate = "translate(-#{x},-#{y})"
  artwork.add_attribute(Attribute.new('transform', translate))
  canvas = svg.root.elements["/svg"]
  canvas.add_attribute(Attribute.new('width', '48'))
  canvas.add_attribute(Attribute.new('height', '48'))
  plate = svg.root.elements["//g[@inkscape:label='plate']"]
  plate.elements.delete_all('')
  svg.root.each_element("//g[@inkscape:label='artwork']/*") do |icon|
    label = icon.attributes['inkscape:label']
    if (label != 'scalable')
      icon.parent.delete_element(icon)
    end
  end
  dir = "Scalable/#{context}"
  File.makedirs(dir) unless File.exists?(dir)
  f = File.open("Scalable/#{context}/#{file}","w")
  svg.write(f, -1, false)
  f.close
  cmd = "#{INKSCAPE} --vacuum-defs -l Scalable/#{context}/#{file} -f Scalable/#{context}/#{file}"
  system(cmd)
end


file = "#{ARGV[0]}.svg"
if (File.exists?("#{SRC}/#{file}"))
  renderit(file)
  puts "\nRendered PNGs from #{SRC}/#{file}"
  expungeit(file)
  puts "\nCreated scalable SVG icon from #{SRC}/#{file}"
else
  puts "[E] No such file (#{file})"
end

