  namespace :db do

    desc "Imports a maxmind release from S3.  If you specify a RELEASE env var, it should be like 2014-07-01 (YYYY-MM-DD).  Otherwise latest found max_mind_releases in db is used."
    task import_maxmind: :environment do |task, args|
    specific_release = ENV['RELEASE']
    if specific_release
      release = MaxMindRelease.find_by_released_at(Date.parse(specific_release))
    else
      release = MaxMindRelease.order('released_at DESC').first
    end

    if release.imported && ENV['REIMPORT'] != '1'
      puts "The MaxMindRelease for #{release.released_at} has already been imported."
      puts "If you really want to import it again, specify REIMPORT=1"
      return
    end

    release.import(ENV['FORCE_FROM_SOURCE'] == '1')
  end

  desc "Import a maxmind blocks (134) database; run like this: rake db:import_geoip_blocks file=<path_to_GeoIPCity-134-Blocks.csv>"
  task import_geoip_blocks: :environment do
    GeoIpBlocks.import_from_max_mind ENV['file']
  end

  desc "Import a maxmind locations (134) database; run like this: rake db:import_geoip_locations file=<path_to_GeoIPCity-134-Location.csv>"
  task import_geoip_locations: :environment do
    GeoIpLocations.import_from_max_mind ENV['file']
  end

  desc "Import a maxmind isp (124) database; run like this: rake db:import_jam_isp file=<path_to_GeoIPISP.csv>"
  task import_jam_isp: :environment do
    JamIsp.import_from_max_mind ENV['file']
  end

  desc "Import a iso3166 country database (countrycodes and names); run like this: rake db:import_countries file=/path/to/iso3166.csv"
  task import_countries: :environment do
    Country.import_from_iso3166 ENV['file']
  end

  desc "Import a region database (countrycode, regioncode, regionname); run like this: rake db:import_regions file=/path/to/region_codes.csv"
  task import_regions: :environment do
    Region.import_from_region_codes(ENV['file'])
  end

  desc "Help"
  task help: :environment do
    puts "bundle exec rake db:import_maxmind"
    puts "bundle exec rake db:import_maxmind_isp file=/path/to/GeoIPISP-142.csv # geo-142"
    puts "bundle exec rake db:import_maxmind_geo file=/path/to/GeoIPCity.csv # geo-139"
    puts "bundle exec rake db:import_geoip_blocks file=/path/to/GeoIPCity-134-Blocks.csv # geo-134"
    puts "bundle exec rake db:import_geoip_locations file=/path/to/GeoIPCity-134-Location.csv # geo-134"
    puts "bundle exec rake db:import_jam_isp file=/path/to/GeoIPISP.csv # geo-124"
    puts "bundle exec rake db:import_countries file=/path/to/iso3166.csv # db/geodata"
    puts "bundle exec rake db:import_regions file=/path/to/region_codes.csv # db/geodata"
  end

  desc "Create a fake set of maxmind data"
  task phony_maxmind: :environment do
    MaxMindManager.active_record_transaction do |manager|
      MaxMindManager.create_phony_database
    end
  end
end
