#!/mod/bin/jimsh

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

set file [cgi_get file]
set urlbase [cgi_get base ""]
set duration [cgi_get duration 1]
set fmts [split [cgi_get fmts ""] ","]
set vc [cgi_get vc ""]

# Default to just downloading the raw file.
set url $file

# Prefer to use DLNA server ... (necessary if encrypted)
set dlna [system dlnaurl [file normalize $url] $urlbase]
if {[llength $dlna]} { 
	set url [lindex $dlna 0]
} elseif {[regexp {^(https?://(.+:.*@)?[[:alnum:].]+(:[[:digit:]]+)?)/} $urlbase x y]} {
	set url "$y$url"
} else {
	set url "http://[system ip]$url"
}
 
if {[file extension $file] in {.ts .TS}} {
	if {![catch {set ts [ts fetch $file]}] && $ts != 0} {
		set duration [$ts duration 1]
		$ts set_watched
	}
}

set file [file tail $file] 
set playlist [file tempfile "[env "TMPDIR" [env "TMP" "/tmp"]]/playXXXXXX"]
set pl ""
try {
	set pl [open $playlist w]
	$pl puts "#EXTM3U"
	$pl puts "#EXTINF:$duration,$file"
	$pl puts "#PLAYLIST:$file" 
	$pl puts $url
} finally {
	if {$pl ne ""} {
		$pl close
	}
}

httpheader "application/x-mpegurl" 0 [list \
	"Content-Disposition" "attachment; filename=\"[file rootname $file].m3u\"" \
  	"Content-Length" "[file size $playlist]" \
  	]
set pl ""
try {
	set pl [open $playlist r]
	$pl copyto stdout
} finally {                                                                  
        if {$pl ne ""} {                                                         
               $pl close
        }
}
catch {file delete $playlist}

