# solar - Aug 31 2004

namespace eval metadata {

#	bind msg - !metadata [namespace current]::msg:pkg
#	bind pub - !metadata [namespace current]::pub:pkg

#	bind msg - !meta [namespace current]::msg:pkg
#	bind pub - !meta [namespace current]::pub:pkg


	proc findpkg {arg} {
		set arg [string tolower $arg]
		set fname "/usr/portage/.ebuild.x"
		if {![file exists ${fname}]} { return "" }
		set fp [open $fname r]
		set line ""
		set cat 0

		if {[string match "*/*" "$arg" ]} { set cat 1 }

		while {[gets $fp line] >= 0} {
			set realname "[file dirname $line]"
			set line [string tolower $line]
	                set match [string tolower $realname]

			if {$cat == 1} {
				if {[string match "$arg" $match]} {
					close $fp
					return "${realname}"
				}
			}
			if {$cat == 0} {
				if {[string match "*/$arg" $match]} {
					close $fp
					return "${realname}"
				}
			}

		}
		close $fp
	}

	proc pkg:lookup { who nick arg } {
		set verbose 0
		
		if {[lindex $arg 0] == "-v"} {
			set verbose 1
			set arg "[lrange $arg 1 end]"
		}

		if {[lindex $arg 0] == "-v" || [lindex $arg 0] == "-vv"} {
			set verbose 2
			set arg "[lrange $arg 1 end]"
		}

		set arg "[lindex [string trim $arg] 0]"
		set stripmagic "_/>=-+1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ:"
		if {[string trim "[string toupper $arg]" "${stripmagic}" ] != ""} {
			set foo [string trim "[string toupper $arg]" "${stripmagic}" ]
			putlog "PKG IS NOT SAFE $arg requested by $who. remaining foo=$foo"
			return 0
		}
		set str "PRIVMSG $who :${nick}:"

		if {$arg == ""} {
			putserv "$str KingTaco says you have invalid syntax. learn how to use me, moron!"
			return 0
		}

		set pkg [[namespace current]::findpkg "${arg}"]

		set len [expr 400 - [string length "${str}"]]
		if {[catch {exec env MAX_LONGDESC_LEN=${len} /var/irc/jeeves/metadata.py $pkg} line] == 0} {
			putserv "$str $line"
			if {$verbose >= 1} {
				set x [lsearch $line "Herd:"]
				set y [lindex $line [expr $x + 1]]
				if {$y != "no-herd"} {
					if {$verbose >= 2} {
						set y "-r $y"
					}
					::herds::pkg:lookup "$who" "$nick" "$y"
				}
			}
		} else {
			putserv "$str there is no metadata info to satisfy what you want to know about $arg or it is an ambiguous package name. Try reading the ChangeLog"
		}
		return 0
	}

	proc msg:pkg {nick uhost hand arg} {
		[namespace current]::pkg:lookup "$nick" "$nick" "$arg"
	}

	proc pub:pkg {nick uhost hand chan arg} {
		[namespace current]::pkg:lookup "$chan" "$nick" "$arg"
	}
}
