
if {![exists -proc _del_bindir]} {

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

	if {[system pkginst undelete]} {
		set _del_dustbin [system dustbin]
	} else {
		set _del_dustbin ""
	}

	proc _del_bindir {file {prefix ""}} {
		global _del_dustbin
		set lbin $_del_dustbin
		if {$prefix ne ""} { append lbin "/$prefix" }
		set dir [file normalize [file dirname $file]]
		regsub "^[file normalize [system mediaroot]]" $dir $lbin ndir
		if {$dir eq $ndir} { set ndir $lbin }
		system mkdir_p $ndir
		return $ndir
	}

	proc _del_touch {file} {
		exec /mod/bin/busybox/touch $file
	}

	proc safe_delete {file {px ""}} {
		global _del_dustbin

		if {![file exists $file]} { return 1 }

		# Check if undelete is installed and that the file being
		# deleted is not already in the dustbin.
		set dustbin 1
		if {$_del_dustbin eq "" || [\
		    string first $_del_dustbin $file] > -1} {
			set dustbin 0
		}

		# Check if files are on same device as mediaroot
		set dir [system mediaroot]
		file stat "$dir/" rootstat
		set rootdev $rootstat(dev)
		file stat $file st
		if {$st(dev) != $rootdev} {set dustbin 0}

		# Directory

		if {[file isdirectory $file]} {
			if {$dustbin} {
				set ndir "[_del_bindir $file $px]/[\
				    file tail $file]"
				while {[file isdirectory $ndir]} {
					append ndir "_"
				}
				file rename $file $ndir
				_del_touch $ndir
			} else {
				file tdelete $file
			}
			return 1
		}

		if {[string match {*.ts} $file]} {
			set ts [ts fetch $file]

			# Check TS validity
			if {![catch {$ts get file}]} {
				if {$dustbin} {
					$ts move [_del_bindir $file $px] 1 1
				} else {
					if {[$ts delete]} {
						return 1
					} else {
						return 0
					}
				}
				return 1
			}
		}

		# otherwise treat as normal file.

		if {$dustbin} {
			set nfile "[_del_bindir $file $px]/[file tail $file]"
			while {[file exists $nfile]} {
				append nfile "_"
			}
			file rename $file $nfile
			_del_touch $nfile
		} else {
			file tdelete $file
		}
		catch {file delete "[file rootname $file].hmi"}
		return 1
	}
}

