#!/mod/bin/jimsh

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

require rsv.class svc.class

set dir /mod/var/backup

httpheader

set file [file tail [cgi_get restore_file test]]
if {$file == 0} {
	puts "No filename supplied."
	exit
}

set ffile "/$dir/$file.rbk"

if {![file exists $ffile]} {
	puts "Backup file <i>$file</i> does not exist."
	exit
}

if {[catch { set fd [open $ffile r] } msg]} {
	puts "Error opening <i>$file</i> - $msg"
	exit
}

puts "Listing scheduled events from <i>$file</i>..."

set fields [[rsv] cleanvars]

set data [split [read $fd] "\n"]
set ver 1

proc event {vals} {
	global fields ver

	set vars {}
	set i 0
	foreach f $fields {
		if {$ver < 2 && $f eq "aulEventToRecordInfo"} continue
		incr i
		lappend vars $f [lindex $vals $i]
	}

	set rsv [rsv new $vars]

	puts "  [$rsv name] ([$rsv channel_name] - [\
	    clock format [$rsv start]] - [\
	    clock format [$rsv end] -format {%H:%M}])"
}

set favnames {}

proc fav {vals} {{lgroup 0}} {
	global favnames

	lassign $vals x group svctype svcname idx

	if {$group != $lgroup} {
		set lgroup $group
		if {[dict exists $favnames $group]} {
			puts "Favourites ($favnames($group))"
		} else {
			puts "Favourites (group $group)"
		}
	}
	puts "  $svcname"
}

proc favname {vals} {
	global favnames

	lassign $vals x num idx name

	puts "Favourites $num '$name'"
	set favnames($idx) $name
}

foreach line $data {
	if {[string match "# version *" $line]} {
		set ver [lindex [split $line " "] 2]
		puts "Backup version $ver"
	}
	set vals [split $line "\t"]
	set type [lindex $vals 0]
	switch -- $type {
		fav -
		favname -
		event { $type $vals }
	    #default { puts "Unhandled '$type'" }
	}
}

close $fd
rsv cleanup

