#!/usr/bin/env ruby
require 'fileutils'
require 'shellwords'

def php_file_contents(filename)
  open(filename).to_a
end

def fix_entity_paths(file_contents)
  file_contents.map do |line|
    if line[/Plugin\\Core\\Entity/]
      line.gsub("\\Plugin\\Core\\Entity", "\\Entity")
    else
      line
    end
  end
end

def entity_paths
  %x[ag --nocolor @EntityType].split("\n").map {|line| line.split(":")[0]}
end

def files_using_entities
  %x[ag --nocolor -l '#{Shellwords.escape("Plugin\\Core\\Entity")}'].split("\n").map {|line| line.split(":")[0]}
end

def entity_dir(old_path)
  "#{old_path[/(^.+)Plugin\/Core\//, 1]}Entity"
end

def new_entity_path(old_path)
  old_path.scan(/(^.+)Plugin\/Core\/(.+$)/).join
end

# Move and rewrite entity files.
entity_paths.each do |entity_path|
  new_path = new_entity_path entity_path
  unless new_path.empty?
    Dir.mkdir entity_dir(entity_path) rescue Errno::EEXIST
    file_contents = fix_entity_paths php_file_contents(entity_path)
    File.open(new_path, 'w') {|f| f.write(file_contents.join) }
    system *["git", "add", new_path]
    FileUtils.rm entity_path
    system *["git", "rm", entity_path]
  end
end

# Rewrite files referencing entities.
files_using_entities.each do |file|
  file_contents = fix_entity_paths php_file_contents(file)
  File.open(file, 'w') {|f| f.write(file_contents.join) }
  system *["git", "add", file]
end