#!/mod/bin/jimsh

package require cgi
source /mod/webif/lib/setup
require ts.class pretty_size system.class

httpheader

set rfile [cgi_get file]
set invert [cgi_get invert]

if {[system inuse $rfile]} {
	puts "This file is in use. Cannot process at the moment."
	exit
}

set ts [ts fetch_or_error $rfile]
if {$ts == 0} { return }
set dir [file dirname $rfile]

set len [$ts duration 1]

set cropstart [clock milliseconds]

set base [file rootname $rfile]
set origdir "$dir/_original"
if {![file exists $origdir]} { file mkdir $origdir }

set shname [file tail $base]
puts "Processing $shname (inverted: $invert)"

if {[file exists "$origdir/$shname.ts"]} {
	puts "This recording already exists within _original"
	puts "Cannot continue."
	exit
}

set bookmarks [$ts bookmarks]

puts "Moving recording to $origdir"

set tail [file tail $base]
foreach ext $tsgroup {
	if {![file exists "$base.$ext"]} continue
	puts "  $tail.$ext"
	file rename "$base.$ext" "${origdir}/$tail.$ext"
}

set cmd [list /mod/bin/nicesplice \
	-in "$origdir/$shname" \
	-out "$dir/$shname"]

if {$invert} {
	if {([llength $bookmarks] % 2) != 0} {
		lappend bookmarks [$ts duration 1]
	}
	foreach k [array names bookmarks] {
		lappend cmd -cut $($k * 10) $($bookmarks($k) * 10)
	}
} else {
	lappend cmd "-cutBookMarks"
}

#puts "CMD: $cmd"

set token [system startop -multiple crop $rfile]
puts [exec {*}$cmd]
system endop $token

set newname "$shname-[clock seconds]"
puts "Renaming file group to $newname"
puts "<span class=hidden id=fileparams file=\"$dir/$newname.ts\"></span>"
ts renamegroup "$dir/$shname.ts" $newname
if {[file executable /mod/bin/sidecar]} {
	set cmd [list /mod/bin/sidecar -n]
	lappend cmd "$dir/$newname"
	puts "Regenerating .nts file"
	puts [exec {*}$cmd]
}

set croptime $(([clock milliseconds] - $cropstart) / 1000.0)
puts "Time taken: $croptime"

