#!/mod/bin/jimsh

source /mod/webif/lib/setup
require ts.class settings.class

source /mod/webif/html/dedup/normalise.jim
source /mod/webif/html/dedup/process.jim

set dirs {}

set auto 0
set doit 0
foreach arg $argv {
	if {$arg eq "-yes"} {
		set doit 1
	} elseif {$arg eq "-auto"} {
		set auto 1
	} else {
		lappend dirs $arg
	}
}
if {![llength $dirs]} { lappend dirs [pwd] }

foreach dir $dirs {
	if {[string index $dir end] eq "/"} {
		set dir [string range $dir 0 end-1]
	}
	if {!$auto} { puts "\[$dir\]" }
	loadseries $dir

	foreach file [lsort -command dedupsort [readdir $dir]] {
		if {[file extension $file] ne ".nts"} { continue }

		set file "$dir/[file rootname $file].hmt"

		set base [file tail [file rootname $file]]
		lassign [dedupprocess $file] stat ts syn fn

		set rdone 0
		set result $stat
		switch $stat {
		    inuse {
			set result "In Use"
		    }
		    dup {
			set result "Duplicate"
			if {$doit} {
				set dupdir "$dir/_duplicates"
				if {![file exists $dupdir]} {
					file mkdir $dupdir
				}
				while {[file exists $dupdir/$fn.hmt]} {
					append fn "~"
				}
				ts renamegroup $file "_duplicates/$fn"
				puts -nonewline "$base -> $result"
				puts " - Renamed to _duplicates/$fn"
				incr rdone
			}
		    }
		    error {
			set result "Cannot process"
		    }
		    nothing {
			set result "Nothing to do"
		    }
		    preserve {
			set result "Preserving"
		    }
		    ok {
			set result $fn
			if {$doit} {
				# Dooooo, it.
				$ts settitle $syn
				$ts set_deduped
				ts renamegroup $file $fn
			}
		    }
		}
		if {!$rdone} {
			if {$auto} {
				if {$result ne "Nothing to do"} {
					puts "$base -> $result"
				}
			} else {
				puts "$base -> $result"
			}
		}
	}
}

