#!/usr/bin/ruby

require 'rubygems'
require 'getoptlong'
require 'esearchy'

@yahoo_key = nil
@bing_key = nil
@maxhits = nil
@domains = []
@output = nil

opts = GetoptLong.new(
[ '--help', '-h', GetoptLong::NO_ARGUMENT ],
['--domain','-d', GetoptLong::REQUIRED_ARGUMENT ],
['--file','-f', GetoptLong::REQUIRED_ARGUMENT ],
['--filter','-p', GetoptLong::REQUIRED_ARGUMENT ],
['--output','-o', GetoptLong::REQUIRED_ARGUMENT ],
['--yahoo_key','-y', GetoptLong::REQUIRED_ARGUMENT ],
['--bing_key','-b', GetoptLong::REQUIRED_ARGUMENT ],
['--maxhits','-m', GetoptLong::REQUIRED_ARGUMENT ]
)

opts.each do |opt, arg|
  case opt
    when '--help':
      # BEGIN OF HELP
      puts "\nHELP for Esearchy\n---------------------\n
      --help, -h
      \tWell I guess you know what this is for (To obtain this Help).\n
      --domain, -d [domain.com]
      \t The domain name to search.\n
      --filter, -p
      \t The pattern to use to filter emails.\n
      --file, -f [file_name] 
      \tIf we need to search more than one domain we can provide a list.\n
      --output, -o
      \tThe output file name.
      Copyright 2009 - FreedomCoder\n"
      #END OF HELP
      exit(0)
    when '--domain':
      @domains << arg
    when '--file':
      if File.exists?(arg)
        open(arg,'r').each_line do |line|
          @domains << line
        end
      else
        puts "File not found"
      end
    when '--yahoo_key':
      @yahoo_key = arg
    when '--bing_key':
      @bing_key = arg
    when '--filter':
      @pattern = arg
    when '--output':
      @output = arg
    when '--maxhits':
      @maxhits = arg
    else
      puts "Unknown command. Please try again"
      exit(0)
  end
end

require 'esearchy'

@domains.each do |domain|
  ESearchy.create domain do |d|
    d.yahoo_key = @yahoo_key if @yahoo_key
    d.bing_key = @bing_key if @bing_key
    d.maxhits = @maxhits if @maxhits
    d.search
    d.save_to_file @output if @output
  end
end
