#!/usr/bin/env ruby

FAST_SHARE_MEM = "{$IFDEF WIN32} FastShareMem, {$ENDIF}"

def set_share_mem(src)
  ret = []
  uses_expr = nil
  src.each_line do |line|
    if line =~ /^uses\b(.*)/
      uses_expr = $1.strip
    elsif uses_expr
      ret.push "uses"
      unless line =~ /\bFastShareMem\b/
        ret.push FAST_SHARE_MEM
      end
      ret.push "  #{uses_expr}" unless uses_expr.empty?
      ret.push line.chomp
      uses_expr = nil
    else
      ret.push line.chomp
    end
  end
  ret.join("\n") << "\n"
end

def set_share_mem_entry(src)
  tmp = src + '~'
  File.rename src, tmp
  open(tmp, 'rb'){|i|
  open(src, 'wb'){|o|
    o.print set_share_mem(i.read)
  }}
end

if __FILE__ == $0
  exts = %w[
    dpr
  ]

  Dir.glob('**/*'){|entry|
    pos = entry.rindex('.')
    next if pos.nil?
    ext = entry[pos+1..-1]
    if exts.include? ext
      $stderr.print "set_share_mem #{entry}\n"
      set_share_mem_entry entry
    end
  }
end
