#!/usr/bin/ruby
# Sort symbols in symbols file to workaround bug #773718

# 1- Scan
symbols = File.readlines(ARGV[0]).collect do |line|
 # Examples of lines we should match:
 # #MISSING: 1.8.15# (optional|c++)"H5::AbstractDs::AbstractDs(H5::AbstractDs const&)@HDF5_CPP_1.8.9" 1.8.13
 #        0                1                                     2="3"                                  4 
 #  H5P_CLS_ATTRIBUTE_CREATE_ID_g@Base 1.8.14
 # 0=nil 1=nil     2=3                    4
 if line =~ /^(#MISSING:.*#)? (\([^\)]+\))?("?(.*)"?) ([^ #]+)$/ then
   $~.captures
 else
   [line]
 end
end

# 2- Bubble sort
#    The sort criteria is <symbol name>@<wersion name> (symbol[3]) without quotes (symbol[3])
symbols.length.times do |index|
  (symbols.length - 1).downto(index) do |i|
    if symbols[i-1].length > 1 and symbols[i].length > 1 then
      symbols[i-1], symbols[i] = symbols[i], symbols[i-1] unless symbols[i-1][3] < symbols[i][3]
    end
  end
end

# 3- Uniq
(symbols.length - 1).downto(1) do |i|
  symbols.delete_at(i) if symbols[i-1].length > 1 and symbols[i].length > 1 and not symbols[i-1][0] and not symbols[i][0] and symbols[i-1][3] == symbols[i][3]
end

# 4- Output
symbols.each do |symbol|
  if symbol.length > 1 then
    puts "#{symbol[0]} #{symbol[1]}#{symbol[2]} #{symbol[4]}"
  else
    puts "#{symbol[0]}"
  end
end
