#!/mod/bin/jimsh

package require cgi
package require sqlite3
source /mod/webif/lib/setup
require altrow

jqplugin tablesorter2
jscss script.js

set databases [glob /var/lib/humaxtv/*.db]
lappend databases {*}[glob /mod/etc/*.db]
lappend databases "/mnt/hd2/dms_cds.db"
lappend databases {*}[glob /mod/var/tvdb/*.db]

header

puts {
<div class=va>
	<img class=va src=/img/db.png height=50>
	&nbsp;
	Database Browser
</div>
}

set ftab [cgi_get tab]
set fdb [cgi_get db]

if {$fdb != 0} {
	puts "<h3><a href=/db/index.jim>Remove filters</a></h3>"
}

proc escape {data} {
	if {[string is print $data]} { return $data }
	set ret ""
	foreach c [split $data ""] {
		if {[string is print $c]} {
			append ret $c
		} else {
			binary scan $c H* hex
			append ret "\\x$hex"
		}
	}
	return $ret
}

proc db_info {db_file} {
	global fdb ftab

	if {$fdb != 0 && [file tail $db_file] ne $fdb} { return }
	if {![file exists $db_file]} { return }

	set db [sqlite3.open $db_file]
	set tables [$db query {
		select name from sqlite_master
		where type='table' order by name
	}]

	puts "<h3><a href=/db/index.jim?db=[file tail $db_file]>
		$db_file</a></h3>"
	
	foreach table $tables {
		set table [lindex $table 1]
		if {$ftab != 0 && $ftab ne $table} { continue }
		set columns [$db query "pragma table_info($table)"]
		set datas [$db query "SELECT * FROM $table order by 1"]
		
		puts "
<h2><a href=/db/index.jim?db=[file tail $db_file]&tab=$table>$table</a></h2>
<table>
	<thead>
		<tr>
		"
		foreach column $columns {
			puts "    <th>[lindex $column 3]</th>"
		}
puts "
		</tr>
	</thead>
	<tbody>
"
		foreach data $datas {
			altrow
			
			for {set i 1} {$i < [llength $data]} {incr i 2} {
				puts "    <td nowrap>[
				    escape [lindex $data $i]]</td>"
			}
			puts "  </tr>"
		}
		puts "
			</tbody>
			</table>
		"
	}
	
	$db close
}

if {$fdb == 0} {
	puts "Please choose database to view:<ul>"
	foreach db [lsort $databases] {
		puts "<li><a href=$::env(SCRIPT_NAME)?db=[file tail $db]>
		    $db</a></li>"
	}
	puts "</ul>"
} else {
	foreach db $databases { db_info $db }
}

footer

