#!/usr/bin/env ruby
require 'csv'

metadata_file = ARGV[0]
properties_file = ARGV[1]

unless !metadata_file.nil? && File.exist?(metadata_file) && File.readable?(metadata_file)
  puts "ERROR: File #{metadata_file} does not exist or is not readable"
  exit 1
end

File.open(properties_file, 'wt') do |f|
  section=''
  CSV.foreach(metadata_file, col_sep: "\t", skip_blanks: true, liberal_parsing: true) do |row|
    if row[0] && row[0][0] == '#'
      section=row[0][1..-1]
      next
    end
    next if section == ''
    case section
    when 'metadataBlock'
      f.puts "metadatablock.name=#{row[1]}"
      f.puts "metadatablock.displayName=#{row[3]}"
    when 'datasetField'
      f.puts "datasetfieldtype.#{row[1]}.title=#{row[2]}"
      f.puts "datasetfieldtype.#{row[1]}.description=#{row[3]}"
      f.puts "datasetfieldtype.#{row[1]}.watermark=#{row[4]}"
    when 'controlledVocabulary'
      x = row[2].unicode_normalize(:nfd)
        .gsub(/\p{InCombiningDiacriticalMarks}+/, '')
        .gsub("\u0141", 'L')
        .gsub("\u0142", 'l')
        .downcase
        .gsub(' ','_')
        .gsub(/([=:\/\\\.])/,'\\\\\1')
        .gsub(/[^ -~]/) {|x| '\u%04X' % x.ord}
      y = row[2]
        .gsub('\\', '\\\\\\\\')
        .gsub(/[^ -~]/) {|x| '\u%04X' % x.ord}
      f.puts "controlledvocabulary.#{row[1]}.#{x}=#{y}"
    else
      puts "WARNING: Unknown section '#{section}'"
    end
  end
end
