#	google v1.24 by (c) cell@isoveli.org
#	Searches the net via google with the given keywords (www.google.com)
#
#	Usage: .google [searchword] [searchword] [.....] [NUMBEROFLINKS]
#	The last parameter is used to define how many links user wants to
#	be displayed
#
#	Use plain 'google' command when using private message.
#
#
#	Visit http://cell.isoveli.org/scripts for more scripts for eggdrop
#

package require cellgen 2.0
namespace eval google {
set scriptversion 1.24

bind pub - !google google::googlepub
bind pub - .google google::googlepub
bind msg - google google::googlemsg


catch { ::cell::registerautoupdate $scriptversion http://cell.isoveli.org/scripts/google.tcl } error


proc googlemsg {nick uhost handle text} {
	::google::googlepub $nick $uhost $handle $nick $text
}


proc googlepub {nick uhost handle chan text} {

	regsub -all -- {\{|\}} $text {} args
	set args [split $args " "]
	if {[string is digit [lindex $args end]]} { set maara [lindex $args end] ; if {$maara>5} { set maara 1 } else { set args [lreplace $args end end] } } else { set maara 1 }
	set args [join $args]
	regsub -all -- { } $args {+} args

	cell::geturl "http://www.google.com/search?q=$args" google::show [list $args $maara $chan]
        putlog "$maara links from google.. ($nick) ($args)"

	cell::wait 2
}


proc show {token} {

	catch {

	set args [cell::getcbargs $token]
	set maara [lindex $args 1]
	set chan [lindex $args 2]
	set args [lindex $args 0]

        set unformattedargs $args
	set args [cell::formatquery $args]

	set foo [cell::geturldata $token]
	set foo [split $foo \n]
	set jaakko 0

	foreach i $foo {

                if {[regexp -nocase -- {Your search.*did not match any documents} $i]} {
                        putserv "PRIVMSG $chan :!google: ($unformattedargs) ei löytynyt mitään"
                        return 0
                }

		if {[regexp -nocase -- {<a class="*l"* href=} $i] && $args != ""} {

			regsub -all -nocase -- {.*class="*l"* href="*} $i {} linkki
			regsub -all -- {" onmousedown.*} $linkki {} linkki
			regsub -all -- {.*http://} $linkki {} linkki
                        append linkit "http://$linkki"

                        incr jaakko
	                if {$jaakko >= $maara} {
				set linkki [cell::formattext $linkki]
				putserv "PRIVMSG $chan :!google: ($unformattedargs) $linkit"
				return 0
       		        } else {
       		                append linkit " - "
       		        }
		}
	}

	if {$jaakko==0} {
		putserv "PRIVMSG $chan :!google: ($unformattedargs) hyöööörrrghhhh"
	} else {
                append linkit ".. linkit loppu"
		putserv "PRIVMSG $chan :!google: ($unformattedargs) $linkit"
        }

	} error
	if {$error != 0 && $error != ""} { putlog "ERROR (google.tcl google::show): $error" }
}

}

putlog "google v$google::scriptversion by cell"
