#!/usr/bin/env ruby
# Author::    Dirk Meyer
# Copyright:: Copyright (c) 2025 - 2025 Dirk Meyer
# License::   Distributes under the same terms as Ruby
# SPDX-FileCopyrightText: 2025-2025 Dirk Meyer
# SPDX-License-Identifier: Ruby

require 'fileutils'

def read_lang( filename )
  list = File.read( filename ).split( "\n" ).map { |e| e.split( ' ', 2 ) }
  list.each_with_object({}) { |(key, value), h| h[key] = value.gsub( '\\', '\\\\' ) }
end

def make_subs( lang )
  @en = read_lang( 'en.txt' )
  @translated = read_lang( "#{lang}.txt" )
  @subs = []
  @en.each_pair do |nr, text|
    next if text == @translated[ nr ]

    @subs.push( [ text, @translated[ nr ] ] )
  end
end

def write_changed( filename, text )
  if File.exist?( filename )
    old = File.read( filename )
    return if old == text
  end
  puts "Saving: #{filename}"
  File.write( filename, text )
end

def translate_file( file, dest )
  text = File.read( file ).split( "\n" )
  text.map! do |line|
    unless line.include?( 'NOTRANSLATE' )
      @subs.each do |(pattern, translated)|
        line.gsub!( pattern) { translated }
      end
    end
    line
  end
  text.push( nil )
  write_changed( dest, text.join( "\n" ) )
end

def translate_dir( lang )
  puts "parsing #{lang}"
  make_subs( lang )
  @dir = "src.#{lang}"
  FileUtils.mkdir_p( @dir )

  files = Dir.glob( [ "src/*.h", "src/[bcpsu]*.c" ] )
  files.each do |file|
    dest = "#{@dir}/#{file.split( '/' ).last}"
    FileUtils.cp( file, dest, preserve: true )
  end
  files = Dir.glob( [ "src/iroffer*.c", "src/dinoex*.c" ] )
  files.each do |file|
    dest = "#{@dir}/#{file.split( '/' ).last}"
    translate_file( file, dest )
  end
end

ARGV.each do |arg|
  translate_dir( arg )
end

exit 0
# eof
