#!/usr/bin/env ruby
require 'yaml'
require 'json'
require 'active_record'
@root_path = File.expand_path(File.dirname(__FILE__))

rails_env = ENV['RAILS_ENV'] || 'development'
config = YAML::load(File.open(@root_path+"/../config/database.yml"))[rails_env]
ActiveRecord::Base.establish_connection (config)

require @root_path+"/../app/models/exploits.rb"

clibase = File.expand_path(File.join(File.dirname(__FILE__), '..', 'fofacli'))

$:.unshift(File.expand_path(File.join(clibase, 'lib')))
.unshift(clibase)
.unshift(File.expand_path(File.join(clibase, 'gem_lib')))


def import_exploit(filename)
  puts "processing #{filename}"

  unless File.exist? filename
    puts "not exists file : #{filename}"
    exit
  end

  content = File.open(filename).read

  require filename
  f = FofaExploits.new

  filename = File.basename(filename)

  e = Exploits.where(filename: filename).take
  e ||= Exploits.new
  e.filename = filename
  e.content = content
  cols = %w|name description author product homepage references fofaquery|
  f.info.each{|k,v|
    if cols.member? k.downcase
      if v.kind_of?(Array) || v.kind_of?(Hash)
        e.send("#{k.downcase}=", v.to_json)
      else
        e.send("#{k.downcase}=", v)
      end
    end
  }
  e.save
end
#puts $:

if ARGV[0]
  import_exploit ARGV[0]
else
  exploits_path = File.expand_path(File.join(clibase, 'exploits'))
  Dir["#{exploits_path}/*.rb"].each do |filename|
    import_exploit filename
  end
end

