#!/usr/bin/env ruby
#
# Copyright (c) 2004, Brian McCallister
# All rights reserved.
#
# This is GPL'ed as it links a GPL'ed library (Ruby/Google) -- sorry
#
# Requires ruby/google available from http://www.caliban.org/ruby/ruby-google.shtml
# Requires ruby 1.8.1


require 'google'
require 'optparse'

query = "Ruby Programming Language" 
start=0
max=10 
filter=false
restrict=nil 
safe=false
lr=nil 
ie=nil 
oe=nil

skip_header=true
key_file = "#{ENV['HOME']}/.google_key"

fields = ["url"]

opts = OptionParser.new do |opts|
    opts.banner = "Usage: google [options] query string which will be concatenated"
    opts.separator ""
    opts.separator "  Options:"
    
    opts.on("-i", "--start NUMBER", "Start index for results") { |num| start = num }
    opts.on("-m", "--max NUMBER", "Max number of results to show") { |num| max = num }
    opts.on("-f", "--[no-]filter", "Activates or deactivates automatic results filtering") { |value| filter = value}
    opts.on("-r", "--restrict VALUE", "Restricts the search") { |value| restrict = value }
    opts.on("-a", "--[no-]safe", "Enable or disable (default disabled) filtering of adult content") { |value| safe = value}
    opts.on("-1", "--lucky", "I'm feeling lucky") { max=1 }
    
    opts.on("-H", "--header", "Print field header on ouput (default disabled)") { skip_header = false }
    opts.on("-s", "--snippet", "Display result snippet in output") { fields << "snippet" }
    opts.on("-t", "--title", "Display result title in output") { fields << "title" }
    opts.on("-u", "--[no-]url", "Show or hide result url in output") {|value| fields.shift unless value }
    
    opts.separator ""
    opts.on("-h", "--help", "Show this message") {exit 0}
    opts.separator("")
    opts.on_tail("Requires Ruby 1.8.1 and Ruby/Google ( http://www.caliban.org/ruby/ruby-google.shtml )")
    opts.on_tail("You can obtain a (free!) google key from http://www.google.com/apis/")
end

if ARGV.length == 0
    puts opts
    exit -1
end

begin
    rest = opts.parse(ARGV)
    query = rest.join(' ')
rescue Exception => msg
    puts opts
    puts msg
    exit -1
end

if !File.exists?(key_file)
  puts "Please get a (free!) google soap key from http://www.google.com/apis/ and put it in ~/.google_key"
  exit -1
end

KEY = File.open(key_file) {|kf| kf.readline.chomp}
google = Google::Search.new(KEY)

query = google.search(query, start, max, filter, restrict, safe)
query.resultElements.each do |result|
    fields.each do |field|
        print "#{field}: " unless skip_header
        puts result.send(field)
    end
end
