#!/mod/bin/jimsh

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

httpheader

cgi_input 1

set cb [[clipboard new {path "/tmp/webif-browse.cb"}] load]

set action [cgi_get act list]

switch $action {
    list {
	if {![$cb size]} {
		puts "<i>Clipboard is empty</i>"
		break
	}
	puts "<div class=cliplist>"
	foreach file [$cb get items] {
		set img "page_white_copy"
		if {[$file get action] eq "cut"} {
			set img "cut"
		}
		set path [$file get path]
		set xpath [cgi_quote_html $path]
		puts "<span title=\"$xpath\" alt=\"$xpath\">"
		puts "<img src=/img/context/$img.png>"
		set dfile [file tail $path]
		if {[string length $dfile] > 25} {
			set dfile "[string range $dfile 0 22]..."
		}
		if {[file isdirectory $path]} {
			puts "<img height=16
			    src=/images/711_1_09_Media_Folder.png>"
		}
		puts [cgi_quote_html $dfile]
		puts "<a class=clipdel href=# alt=\"Remove\" title=\"Remove\"
		    path=\"[cgi_quote_url $path]\">
		    <img border=0 src=/img/close.png height=16></a>"
		puts "</span>"
	}
	puts "</div>"
	puts "<button id=paste>Paste to current folder</button>"
	puts "<button id=clipclear>Empty clipboard</button>"
    }
    add {
	if {[set path [cgi_get path]] eq "0"} {
		puts "No path."
		exit
	}
	set dir [cgi_unquote_input [cgi_get dir]]
	set mode [cgi_get mode copy]
	foreach p $path {
		set p [cgi_unquote_input $p]
		if {$dir ne "0" && [string first "$dir/" $p] != 0} {
			puts "$p not in directory<br>"
			continue
		}
		if {![$cb present $p]} {
			$cb add $mode $p
			puts "Added $p for $mode<br>"
		}
	}
	$cb save
    }
    remove {
	$cb remove [cgi_unquote_input [cgi_get path]]
	$cb save
    }
    clear {
	$cb clear
	$cb save
    }
    paste {
	set dir [cgi_unquote_input [cgi_get dir]]
	foreach item [$cb get items] {
		set path [$item get path]
		set file [file tail $path]
		set mode [$item get action]

		puts "Pasting $file"

		if {[file isdirectory $path]} {
			# Directory
			if {$mode eq "cut"} {
				catch {file rename $path "$dir/$file"}
			} else {
				catch {puts [exec /mod/bin/busybox/cp -r \
				    $path $dir]}
			}
		} elseif {[string match {*.ts} $path]} {
			set ts [ts fetch $path]
			if {![catch {$ts get file}]} {
				foreach f [$ts fileset] {
					if {$mode eq "cut"} {
						catch {file rename $f \
						    "$dir/[file tail $f]"}
					} else {
						catch {file copy $f \
						    "$dir/[file tail $f]"}
					}
				}
			}
		} else {
			if {$mode eq "cut"} {
				catch {file rename $path \
				    "$dir/[file tail $path]"}
			} else {
				catch {file copy $path \
				    "$dir/[file tail $path]"}
			}
		}
	}
	$cb clear
	$cb save
    }
}