#!/usr/bin/env ruby
require 'active_support/all'
require 'uglifier'
require 'fileutils'

def replace_files(files, &block)
  Array.wrap(files).each do |file|
    file_path = File.join('public/assets', file)
    contents = File.read(file_path)
    block.call(contents)
    File.open(file_path, 'w+'){|f| f.puts contents}
  end
end

def gsub_file(file, find, replace)
  replace_files file do |contents|
    contents.gsub! find, replace
  end
end

def compress_js(*files)
  replace_files files do |contents|
    contents.replace Uglifier.compile(contents, screw_ie8: true)
  end
end

def gsub_all_scripts(find, replace)
  extensions = %w[js]
  Dir.glob(File.join('public/assets/**', "*.{#{extensions.join(',')}}")).each do |asset_path|
  end
end

def remove(*files)
  files = files.first if files.first.is_a? Array
  files.each do |file|
    FileUtils.rm_rf(File.join('public/assets', file))
  end
end

remove 'user/app/application.js' # embedded in flat/application

gsub_file 'user/foundation/application.css', /url\(("?)\/assets/, 'url(\1../..'
gsub_all_scripts 'src="/assets', 'src="./assets'

compress_js 'user/flat/application.js'
