#!/mod/bin/jimsh

package require sqlite3
package require cgi
source /mod/var/mongoose/lib/setup
require ts.class system.class

puts "Content-Type: text/html\r\n\r\n"

cgi_input
#cgi_dump

set rfile [cgi_get file]
set ts [ts fetch $rfile]
set dir [file dirname $rfile]
set len [$ts duration 1]

if {[cgi_get do] eq "it"} {
	set xstart [clock milliseconds]

	set base [file rootname $rfile]
	set shname [file tail $base]
	puts "Processing $shname"

	puts [exec /mod/bin/ffmpeg -y -benchmark -v 0 \
	    -i $rfile -f mp3 \
	    -vn -acodec copy "${base}.mp3"]

	if {[system pkginst id3v2]} {
		puts [exec /mod/bin/id3v2 \
		    --song "[$ts get title]" \
		    --comment "[$ts get synopsis]" \
		    --album "[$ts get channel_name]" \
		    --year "[clock format [$ts get start] -format {%Y}]" \
		    "${base}.mp3"]
	}

	set xtime [expr [expr [clock milliseconds] - $xstart] / 1000.0]
	puts "Time taken: $xtime"

	exit
}

header

puts "
<link href=/css/jquery.progressbar.css rel=stylesheet type=text/css />
<script type=\"text/javascript\" src=\"/js/jquery.progressbar.js\"></script>

<table class=keyval cellpadding=5>
<tr><th>File:</th><td>$rfile</td></tr>
<tr><th>Length:</th><td>[clock format $len -format "%T"]</td></tr>
</table>
"

puts {

<div style="margin-top: 10px"></div>
<div id=audiodiv><button id=audioit>Perform audio extraction</button></div>
<div id=progressdiv style="display: none">
Extracting audio: <div id=progressbar></div>
}
puts "<button id=back
    dir=\"[cgi_quote_url $dir]\"
    rfile=\"[cgi_quote_url $rfile]\"
    style=\"display: none\">Back to media list</button>"
puts {
<div id=output class=pre style="margin-top: 10px"></div>
</div>

<script type=text/javascript>

var handle = 0;

function update()
{
	$.get('/cgi-bin/browse/audio_progress.jim?file='
	    + $('#back').attr('rfile'), function(data) {
		if (handle)
			$('#progressbar').reportprogress(data);
	});
}

$(document).ready(function() {

$('#progressbar').reportprogress(0);

$('#back').button().click(function() {
	window.location = '/cgi-bin/browse.jim?dir=' + $(this).attr('dir');
});

$('#audioit').button().click(function() {
	$('#audiodiv').hide('slow');
	$('#progressdiv').show('slow');
	handle = setInterval("update()", 1000);
	$('#output').load(document.URL + '&do=it', function() {
		clearInterval(handle);
		handle = 0;
		$('#back').show();
		$('#progressbar').reportprogress(100);
	});
});

});
</script>
</div>

}

