#!/usr/bin/env ruby

require "fileutils"

def usage
  puts <<-usage
Usage: script/ic_launcher directory

Directory should contain pngs with filenames in the format:

app_blue_36x36.png
app_blue_48x48.png
..
app_blue_192x192.png
app_green_36x36.png
app_green_48x48.png
..
app_green_192x192.png

Each icon will be copied to the appropriate destination.
usage
end

# Given a filename for an icon, return what directories the file should be copied to.
def destinations_from_filename(filename)
  match = filename.match(/\Aapp_(?<color>[a-z]+)_(?<dimensions>\d+x\d+)\.png\z/)
  return [] unless match[:color] && match[:dimensions]
  density = density_from_dimensions(match[:dimensions])
  return [] unless density

  variants_from_color(match[:color])
    .map { |v| File.join(root, "app/src/#{v}/res/mipmap-#{density}/ic_launcher.png") }
end

def density_from_dimensions(dimensions)
  {
    "48x48"     => "mdpi",
    "72x72"     => "hdpi",
    "96x96"     => "xhdpi",
    "144x144"   => "xxhdpi",
    "192x192"   => "xxxhdpi"
  }[dimensions]
end

def variants_from_color(color)
  {
    "blue"      => ["main"],
    "green"     => ["internalMin21Release", "internalPre21Release"]
  }[color].to_a
end

def root
  File.absolute_path(File.join(File.expand_path(__FILE__), "..", ".."))
end

def source_files(directory)
  Dir.glob(File.join(File.expand_path(directory), "*.png"))
end

if __FILE__ == $0
  if ARGV[0].nil?
    usage
    return
  end

  source_files(ARGV[0]).map { |source|
    puts "---"
    puts "Source: #{File.basename(source)}"
    destinations_from_filename(File.basename(source))
      .map { |destination|
        puts "Destination: #{destination}"
        FileUtils.cp(source, destination)
      }
  }
end
