require "rubygems"
require "optimist"

OPTS = Optimist::options do
    banner <<-EOS
Import an archive generated by import_site_archive.rb into the current
database. This presumes the current database has its schema setup and that
there won't be any primary key conflicts (i.e. the db should be empty)

Usage:

  rails runner tools/import_site_archive.rb PATH_TO_ARCHIVE

To load an archive into a new db that you've added to database.yml under your
current environment:
  
  dropdb DBNAME
  rake db:setup
  rails r tools/import_site_archive.rb PATH_TO_ARCHIVE

where [options] are:
EOS
  opt :debug, "Print debug statements", :type => :boolean, :short => "-d"
end

start_time = Time.now
@archive_path = ARGV[0]
unless File.exist? @archive_path
  Optimist::die "Archive does not exist"
end

@work_path = Dir.mktmpdir
FileUtils.mkdir_p @work_path, :mode => 0755

def system_call(cmd)
  puts "Running #{cmd}" if OPTS[:debug]
  system cmd
end

system_call "cp #{@archive_path} #{@work_path}/"
system_call "cd #{@work_path} && unzip #{File.basename(@archive_path)}"
Dir.glob(File.join(@work_path, '*.csv')).each do |path|
  table_name = File.basename(path).split('.')[0]
  puts
  puts table_name.humanize.upcase
  unless klass = Object.const_get(table_name.singularize.classify)
    puts "ERROR: couldn't load model for #{table_name}"
    next
  end
  columns = klass.column_names.sort.map{|c| "\\\"#{c}\\\""}.join(',')
  system_call "psql #{ActiveRecord::Base.connection.current_database} -c \"\\copy #{table_name} (#{columns}) FROM '#{path}' CSV HEADER\""
end

puts "Imported #{@archive_path} in #{Time.now - start_time} s"
