#!/usr/bin/tclsh

#set log [open /tmp/log w]

puts "Content-Type: text/html"
puts ""

set perms $env(DOCUMENT_ROOT)/upload/permissions

set user $env(HTTP_X_USER)
set password $env(HTTP_X_PASSWORD)

set file $env(HTTP_X_DEST)
regsub -all \\.\\. $file "" file

#puts $log "file = $file"; flush stdout

if [file exists $perms] {
    set ok 0
    set fp [open $perms r]
    while {![eof $fp]} {
	set line [gets $fp]
#puts $log "pline = $line"; flush stdout

	if {[lindex $line 0] == $user} {
	    if {[lindex $line 1] == $password} { set ok 1 }
	    if {$ok && ([llength $line] > 2)} {
		set ok 0
	    	foreach pat [lrange $line 2 end] {
		    if [string match $pat $file] { set ok 1; break }
		}
	    }
	    break
	}
    }
#puts $log "ok = $ok"; flush stdout

    if !$ok {
	puts "0 You don't have permission to upload $file."
	exit 0
    }
}

set dfile $env(DOCUMENT_ROOT)/$file
if ![file exists [file dirname $dfile]] { 
    file mkdir [file dirname $dfile] 
}
set fp [open $dfile w]
puts -nonewline $fp [read stdin $env(CONTENT_LENGTH)]
close $fp

puts "1 File $file has been successfully uploaded."

exit 0
