require "rubygems"
require "rake/clean"

def locate_mime_database
  possible_paths = [
    (File.expand_path(ENV["FREEDESKTOP_MIME_TYPES_PATH"]) if ENV["FREEDESKTOP_MIME_TYPES_PATH"]),
    "/usr/local/share/mime/packages/freedesktop.org.xml",
    "/opt/homebrew/share/mime/packages/freedesktop.org.xml",
    "/usr/share/mime/packages/freedesktop.org.xml"
  ].compact
  path = possible_paths.find { |candidate| File.exist?(candidate) }
  
  return path unless path.nil?
  raise(<<~ERROR)
   Could not find MIME type database in the following locations: #{possible_paths}
   
   Ensure you have either installed the shared-mime-types package for your distribution, or 
   obtain a version of freedesktop.org.xml and set FREEDESKTOP_MIME_TYPES_PATH to the location 
   of that file.
  ERROR
end

desc "Build a file pointing at the database"
task :default do
  mime_database_path = locate_mime_database
  open("../../lib/mimemagic/path.rb", "w") do |f|
    f.print(%Q{
      class MimeMagic
        DATABASE_PATH="#{mime_database_path}"
      end
    })
  end
end