#!/usr/bin/env ruby

require 'optparse'
require 'pathname'

options = {}
option_parser = OptionParser.new do |opts|
  opts.banner = "Usage: #{$0} [options] [res-pp/MODULE-pp.svg] [...more files...]"
  opts.on_tail('-h', '--help', 'Show this message') do
    puts opts
    exit
  end
end
begin
  option_parser.parse!
rescue => e
  STDERR.puts e.to_s
  STDERR.puts "\n"
  STDERR.puts option_parser.help
  exit 1
end
if ARGV.empty?
  STDERR.puts option_parser.help
  exit 1
end

ARGV.each do |svg_file|
  unless File.readable?(svg_file)
    STDERR.puts "No such file: #{svg_file}"
    exit 1
  end
  slug = nil
  if File.basename(svg_file) =~ /^(.*)-pp.svg$/
    slug = $1
  else
    STDERR.puts "Input file #{file} must be named *-pp.svg"
    exit 1
  end

  cpp_file = Pathname.new(File.join(File.dirname(svg_file), '..', 'src', "#{slug}.cpp")).cleanpath
  if File.readable?(cpp_file)
    cpp = File.read(cpp_file)
    if cpp =~ /\n([ \t]+)\/\/ generated by svg_widgets\.rb.*\/\/ end generated by svg_widgets\.rb/m
      spaces = $1

      cmd = "#{File.join(File.dirname($0), 'svg_widgets.rb')} --variables #{svg_file}"
      out = `#{cmd}`
      unless $?.success?
        STDERR.puts "Calling '#{cmd}' failed:\n#{out}"
        exit 1
      end
      if out =~ /auto/
        out.gsub!(/auto/, "#{spaces}auto")
        new_cpp = cpp.sub(/(\/\/ generated by svg_widgets\.rb).*(\/\/ end generated by svg_widgets\.rb)/m, "\\1\n#{out}#{spaces}\\2")
        if new_cpp != cpp
          File.write(cpp_file, new_cpp)
          puts "Wrote: #{cpp_file}"
        else
          puts "Unchanged: #{cpp_file}"
        end
      else
        STDERR.puts "#{cmd} didn't produce any variables"
      end
    else
      STDERR.puts "Module source file doesn't seem to have replaceable variables: #{cpp_file}"
    end
  else
    STDERR.puts "Module source file doesn't exist: #{cpp_file}"
  end
end
