#!/mod/bin/jimsh

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

httpheader

set file [cgi_get renamefile "-"]
if {$file eq "-"} exit

set newfile [string trim [cgi_get rename]]
set dir [file dirname $file]

if {[file isdirectory $file]} {
	#puts "Directory."
	if {$newfile ne ""} {
		set newfile "${dir}/${newfile}"
		file rename $file $newfile
	}
} elseif {[set ts [ts fetch $file]] != 0} {
	#puts "TS file."

	foreach attr {title synopsis guidance genre} {
		if {[catch {
			set new [string map {"\n" ""} [
			    string trim [cgi_get "rename_$attr"]]]
			set old [$ts get $attr]
			if {$attr eq "genre"} {
				set new [ts genre $new]
			}
			if {$new ne $old} {
				if {$attr eq "guidance" || $new ne ""} {
					$ts set$attr $new
				}
			}
		} msg]} {
			stderr puts "$attr: $msg"
		}
	}
	# deal with series number/ep num/ep total, which get set together
	# list the old values seen in case a later one is changed
	set epdataold {}
	# list values to be set, or {}
	set epdatanew {}
	foreach attr {seriesnum episodenum episodetot} {
		if {[catch {
			set new [string map {"\n" ""} [
			    string trim [cgi_get "rename_$attr"]]]
			set old [$ts get $attr]
			if {$new ne $old} {
				switch $attr {
					seriesnum {
						set epdatanew [list $new]
					}
					episodenum -
					episodetot {
						if {$epdatanew eq {}} {
						    set epdatanew $epdataold
						}
						lappend epdatanew $new
					}
				}
			} elseif {$epdatanew eq {}} {
				# nothing to be changed yet
				lappend epdataold $old
			} else {
				# fill to-be-set list with old value
				lappend epdatanew $old
			}
		} msg]} {
			stderr puts "$attr: $msg"
		}
	}
	if {$epdatanew ne {}} {
		if {[catch {$ts storeepisode $epdatanew} msg]} {
                        puts "ts::storeepisode: $msg"
                }
	}

	if {"$dir/$newfile.ts" ne "$file"} { ts renamegroup $file $newfile }
} else {
	#puts "Normal file."
	if {$newfile ne ""} {
		set newfile "$dir/$newfile[file extension $file]"
		puts "Rename ($file) -> ($newfile)"
		file rename $file $newfile
	}
}

