#!/mod/bin/jimsh

package require cgi
source /mod/webif/lib/setup
require json

httpheader "application/json"

set dir [cgi_get dir "/media/My Video"]
set dlen [string length "$dir/"]

#9.4G	/media/My Video/Archive
#1.4G	/media/My Video/CSI_ Crime Scene Investigation
puts "{"
if {[catch {exec /mod/bin/busybox/du -h -l -d 1 "$dir/"}  dutxt]} {
	set dutxt ""
}
foreach line [split $dutxt "\n"] {
	lassign [split $line "\t"] size node
	set node [string range $node $dlen end]
	if {[string length $node]} {
		puts "\"[jescape $node]\": \"$size\","
	}
}

# Handle symbolic links.
foreach file [readdir $dir] {
	set file "$dir/$file"
	if {[catch {set lk [file readlink $file]}]} continue

	if {![string match "/*" $lk]} { set lk "$dir/$lk" }

	if {![file isdirectory $lk]} continue
	if {[catch {exec /mod/bin/busybox/du -h "$lk"}  dutxt]} {
		set dutxt ""
	}
	foreach line [split $dutxt "\n"] {
		set fields [split $line "\t"]
		if {[lindex $fields 1] eq $lk} {
			set node [file tail $file]
			set size [lindex $fields 0]
			puts "\"[jescape $node]\" : \"@$size\","
		}
	}
}

if {[catch {exec /mod/bin/busybox/du -hs "$dir/"}  dutxt]} {
	set dutxt "N/A"
}
lassign [split $dutxt] total
puts "\"\": \"$total\""

puts "}"

