#!/mod/bin/jimsh

require system.class

proc dedupprocess {file} {{seen {}}} {
	set ts [ts fetch $file 1]

	if {[$ts flag "Deduped"]} {
		# Fast track content which has already been de-duped.
		set fn [file rootname [file tail $file]]
		if {$fn in $seen} { set stat dup } else { set stat nothing }
		lappend seen $fn
		return [list $stat $ts "" $fn]
	}

	set dir [file dirname $file]
	set base [file tail [file rootname $file]]
	set syn [dedupnormalise [$ts get synopsis] [$ts get title]]
	# Escape special characters to create the filename.
	set fn [system filename $syn]

	set stat ok
	if {[$ts inuse]} {
		set stat inuse
	} elseif {$fn in $seen} {
		set stat dup
	} elseif {[string length $syn] > 40} {
		set stat error
	} elseif {$base eq $fn} {
		set stat nothing
		$ts set_deduped
	} elseif {[file exists "$dir/$fn.ts"]} {
		set stat preserve
	}

	lappend seen $fn

	return [list $stat $ts $syn $fn]
}

