#!/mod/bin/jimsh

package require cgi
source /mod/webif/lib/setup
require pkg.class system.class settings.class

cgi_input
#cgi_dump

set cmd [cgi_get cmd update]

proc putsf {str} {
	puts $str
	flush stdout
}

proc opkg {cmd {silent 0}} {
	if {!$silent} { putsf ">>> opkg $cmd" }
	set bcmd "|/mod/webif/lib/bin/opkg $cmd"
	set fd [open $bcmd r]
	while {[gets $fd line] >= 0} {
		putsf "$line"
	}
	close $fd
	putsf ""
}

# Google Chrome won't render chunks with text/plain!
# https://bugs.chromium.org/p/chromium/issues/detail?id=156023
#httpheader "text/plain"
httpheader "application/octet-stream"

set cmdargs [lassign $cmd cmd]

set netcmds {install update upgrade}

if {$cmd in $netcmds && ![system connectivity]} {
	putsf "!!  ERROR - No network connectivity to package repository  !!"
	putsf "Check your Internet connection and DNS service and then try again."
	exit
}

if {$cmd eq "dependinfo"} {
	putsf ">>> What $cmdargs depends on\n"
	opkg "depends $cmdargs" 1

	putsf ">>> What depends on $cmdargs\n"
	set bcmd "|/mod/webif/lib/bin/opkg whatdepends $cmdargs"
	set fd [open $bcmd r]
	while {[gets $fd line] >= 0} {
		if {[string match "What depends on root set" $line]} break
	}
	while {[gets $fd line] >= 0} {
		if {[string match "*depends on $cmdargs*" $line]} {
			puts "$line"
		}
	}
	close $fd
	putsf ""
	exit
}

if {$cmd eq "upgrade"} { opkg update }

if {$cmd eq "remove" && [[settings] noautoremove] ne "1"} {
	append cmd " --autoremove"
}

opkg "$cmd $cmdargs"

if {$cmd eq "update" || $cmd eq "upgrade"} {
	putsf "Updating package meta information"
	pkg fetchmeta
	putsf "Done."
	putsf ""
	putsf "Updating diagnostic meta information"
	pkg fetchdiagmeta
	putsf "Updating MUX database"
	pkg fetchmuxdb
}

putsf "Done."

