if {![exists -proc class]} { package require oo }

class pkg {
	name		""
	latest		""
	descr		""
	installed	""
}

set ::pkgmeta {}
set ::diagmeta {}

pkg method _load {nm} {
	set name $nm
	foreach line [split [exec /bin/opkg list $nm] "\n"] {
		# betaftpd - 0.0.8pre17-1 - Description...
		regexp {^[^ ]+ - ([^ ]+) - (.*)$} $line x latest descr
	}
	set info [exec /bin/opkg list-installed $nm]
	regexp {^([^ ]+) - ([^ ]+)$} $info full xname installed

	return $self
}

proc {pkg load} {nm} {
	return [[pkg] _load $nm]
}

pkg method is {what} {
	switch $what {
		installed {
			if {$installed eq ""} { return 0 }
			return 1
		}
		upgradable {
			if {$installed eq $latest} { return 0 }
			return 1
		}
	}
	return 0
}

proc {pkg avail} {} {
	set inst_pkgs [pkg inst]
	set avail_pkgs {}
	foreach pkg [split [exec /bin/opkg list] "\n"] {
		if [regexp {^ } $pkg] { continue }
		if {[regexp {^([^ ]+)} $pkg name] == 0} { continue }
		if {$name ni $inst_pkgs} { lappend avail_pkgs $name }
		#puts "New: $name<br>"
	}
	return $avail_pkgs
}

proc {pkg inst} {} {
	# Build a list of installed packages - just the names
	set inst_pkgs {}
	foreach pkg [split [exec /bin/opkg list-installed] "\n"] {
		if {[regexp {^([^ ]+)} $pkg name] == 0} { continue }
		lappend inst_pkgs $name
		#puts "Inst: $name<br>"
	}
	return $inst_pkgs
}

proc {pkg upgr} {} {
	#webif - 0.5.3 - 0.5.7
	set upgr_pkgs {}
	foreach pkg [split [exec /bin/opkg list-upgradable] "\n"] {
		if {[regexp {^([^ ]+)} $pkg name] == 0} { continue }
		lappend upgr_pkgs $name
		#puts "Upgr: $name<br>"
	}
	return $upgr_pkgs
}

proc {pkg loadmeta} {} {
	if {[llength $::pkgmeta]} { return }
	if {![file exists "/mod/var/pkg.meta"]} {
		catch {pkg fetchmeta}
	} else {
		set meta [open "/mod/var/pkg.meta" r]
		set ::pkgmeta [read $meta]
		$meta close
	}
}

proc {pkg loaddiagmeta} {} {
	if {[llength $::diagmeta]} { return }
	if {![file exists "/mod/var/diag.meta"]} {
		catch {pkg fetchdiagmeta}
	} else {
		set meta [open "/mod/var/diag.meta" r]
		set ::diagmeta [read $meta]
		$meta close
	}
}

proc {pkg fetchmeta} {} {
	set f [socket stream hummypkg.org.uk:80]
	$f puts -nonewline "GET /hdrfoxt2/pkg.meta HTTP/1.1\r\n"
	$f puts -nonewline "Host: hummypkg.org.uk\r\n"
	$f puts -nonewline "\r\n"

	set line [string trim [$f gets]]
	while {[string length $line]} {
		set line [string trim [$f gets]]
	}
	set ::pkgmeta [$f read]
	$f close

	set ff [open "/mod/var/pkg.meta" w]
	puts $ff $::pkgmeta
	$ff close
}

proc {pkg fetchdiagmeta} {} {
	set f [socket stream hummypkg.org.uk:80]
	$f puts -nonewline "GET /diag/diag.meta HTTP/1.1\r\n"
	$f puts -nonewline "Host: hummypkg.org.uk\r\n"
	$f puts -nonewline "\r\n"

	set line [string trim [$f gets]]
	while {[string length $line]} {
		set line [string trim [$f gets]]
	}
	set ::diagmeta [$f read]
	$f close

	set ff [open "/mod/var/diag.meta" w]
	puts $ff $::diagmeta
	$ff close
}