#! /usr/bin/env ruby
# frozen_string_literal: true

#
#  examine the nokogiri dll for external symbols that shouldn't be there
#
#  this assumes that we're on a linux machine, and that nokogiri.so, libxml2.a, libxslt.a, and
#  libexslt.a exist and can be found under the pwd.
#

def find_that_file(glob)
  Dir.glob(glob).first || raise("could not find #{glob}")
end

def find_symbols(archive, flavor)
  %x(nm #{archive}).split("\n").grep(/ #{flavor} /).each_with_object(Set.new) do |line, set|
    set.add(line.split(/\s/).last)
  end
end

def external_symbols(archive)
  find_symbols(archive, "T")
end

def local_symbols(archive)
  find_symbols(archive, "t")
end

noko_so = find_that_file("lib/**/nokogiri.so")
libxml2_archive = find_that_file("ports/**/libxml2.a")
libxslt_archive = find_that_file("ports/**/libxslt.a")
libexslt_archive = find_that_file("ports/**/libexslt.a")
libgumbo_archive = find_that_file("tmp/**/libgumbo.a")

symbols = external_symbols(noko_so)
symbols -= external_symbols(libxml2_archive)
symbols -= external_symbols(libxslt_archive)
symbols -= external_symbols(libexslt_archive)
symbols -= external_symbols(libgumbo_archive)

puts "#{noko_so} exports the following surprising symbols:"
symbols.to_a.sort.each do |symbol|
  next if symbol == "Init_nokogiri"
  next if /^Nokogiri_/.match?(symbol)
  next if /^noko_/.match?(symbol)

  puts "- #{symbol}"
end

symbols = local_symbols(noko_so)

puts "#{noko_so} has the following surprising local symbols:"
symbols.to_a.sort.each do |symbol|
  puts "- #{symbol}" if /^noko_|^Nokogiri_/.match?(symbol)
end
