
# This is another funny but not "ha ha" funny thing.  In production mode, the
# Rails asset pipeline takes our LESS files, grinds away, and spits out static
# CSS, compressed, compiled, etc..  This is a problem for us because it assumes
# that the paths to any assets referenced within the CSS are known at the time
# precompilation takes place.
#
# For ArchivesSpace, this isn't true: you can set an application URL prefix in
# your configuration and change it however often you like.  The side-effect of
# this is that the paths generated by the asset pipeline will no longer be
# correct--it's expecting to find stuff under /assets, not
# /your-awesome-prefix/assets.  Then stuff breaks and the whole thing looks
# stupid.
#
# After careful consideration, we fixed this in the most ham-fisted way we could
# imagine.  We rewrite the pre-compiled CSS files to fix the paths on startup!
# I know, right?!  We did this because all of the other ideas we had were even worse:
#
#  * We could write a servlet filter to rewrite them on the fly, but it would
#    only work for Jetty users.
#
#  * We could stop precompiling all together (or do so when the app starts up),
#    and slow down app startup times.
#
#  * We could Base64 encode the assets and inline them straight into the CSS,
#    and then everyone could redownload all of Font Awesome whenever we made a
#    tiny CSS change!
#
# So you see, we were once regular people like you.  Regular people, in a
# desparate situation.  Now, dead inside.
#
# Cheers and beers,
#
# Mark & Payten
#


require 'zlib'

class AssetPathRewriter

  def rewrite(prefix, base_dir)
    base_dir = File.absolute_path(base_dir)

    unless prefix.end_with?('/')
      prefix = "#{prefix}/"
    end

    if Dir.exist?(base_dir)
      success = false

      1000.times do
        if File.basename(base_dir) == "webapp"
          success = true
          break
        elsif base_dir == File.dirname(base_dir)
          break
        else
          base_dir = File.dirname(base_dir)
        end
      end

      return unless success

      rewrite_files = Dir.glob(File.join(base_dir, "assets", "**", "*.css"))
      rewrite_files.each { |file| rewrite_for_prefix(file, prefix) }
    end
  end

  private

  def rewrite_for_prefix(path, prefix)
    begin
      css = File.read(path)
      css.gsub!(%r{url\(/assets/}, "url(#{prefix}assets/")
      css.gsub!(%r{url\("/assets/}, "url(\"#{prefix}assets/")
      css.gsub!(%r{url\('/assets/}, "url('#{prefix}assets/")
      File.open(path, "w") do |fh|
        fh.write(css)
      end

      if File.exist?(path + '.gz')
        Zlib::GzipWriter.open(path + '.gz') do |gz|
          gz.write css
        end
      end
    rescue Exception => e
      throw Exception.new "failed to rewrite #{path} for #{prefix} - #{e.message}"
    end
  end
end
