#!/mod/bin/jimsh

package require cgi
source /mod/webif/lib/setup
require settings.class plugin system.class spinner.class

httpheader

if {[cgi_get act] eq "https"} {
	set val [cgi_get val off]
	if {$val in {0 off}} {
		exec /mod/webif/lib/bin/mkcert -delete
		puts "HTTPS Server will be disabled after next reboot."
	} else {
		exec /mod/webif/lib/bin/mkcert
		puts "HTTPS Server will be enabled after next reboot."
	}
	exit
}

if {[cgi_get act] eq "xtelnet"} {
	set val [cgi_get val off]
	if {$val in {0 off}} {
		file delete /mod/boot/xtelnet
		puts "Telnet server expert mode will be disabled after next reboot."
	} else {
		exec /mod/bin/busybox/touch /mod/boot/xtelnet
		puts "Telnet server expert mode will be enabled after next reboot."
	}
	exit
}

set settings [settings new]

set hostname [$settings hostname]
set smtp_server [$settings smtp_server]
set channel_group [$settings channel_group]
set epg_style [$settings epg_style]
set service_style [$settings service_style]
set pkgdev [$settings pkgdev]
set notoolbar [$settings notoolbar]
set nomobile [$settings nomobile]
set nohelplinks [$settings nohelplinks]
set notwitfeed [$settings notwitfeed]
set nounwatchedcount [$settings nounwatchedcount]
set chanchangenc [$settings chanchangenc]
set xepghours [$settings xepghours]
if {$xepghours == 0} { set xepghours 4 }
set genrededup [$settings genrededup]
set autolog [$settings autolog]
set audiomp3 [$settings audiomp3]

# Handle updates

if {![dict exists $env SCRIPT_NAME]} { set env(SCRIPT_NAME) "" }

proc _handle_update {class var old text} {
	global _cgi
	global settings

	if {[dict exists $_cgi $var]} {
		set new [string trim [dict get $_cgi $var]]
		if {$new == $old} {
			puts "$text unchanged."
		} elseif [string is $class -strict $new] {
			$settings $var $new
			puts "$text updated."
		} else {
			puts "Invalid value for $var."
		}
		exit
	}
}

proc handle_int_update {var old {text "Value"}} {
	_handle_update digit $var $old $text
}

proc handle_str_update {var old {text "Value"}} {
	_handle_update alnum $var $old $text
}

handle_str_update hostname $hostname Hostname
_handle_update ascii smtp_server $smtp_server "SMTP Server"
handle_int_update channel_group $channel_group "Channel Group"
handle_int_update xepghours $xepghours "Grid EPG Hours"
handle_str_update epg_style $epg_style "EPG Type"
handle_str_update service_style $service_style "EPG Channel Type"
handle_int_update pkgdev $pkgdev "Development Package Display"
handle_int_update notoolbar $notoolbar "Disable toolbar"
handle_int_update nomobile $nomobile "Disable mobile link"
handle_int_update nohelplinks $nohelplinks "Disable help links"
handle_int_update notwitfeed $notwitfeed "Disable twitter feed ticker"
handle_int_update chanchangenc $chanchangenc \
    "Disable channel change confirmation"
handle_int_update nounwatchedcount $nounwatchedcount "Disable unwatched count"
handle_int_update genrededup $genrededup "Genre search dedup"
handle_int_update autolog $autolog "Auto-processing log level"
handle_int_update audiomp3 $audiomp3 "MP3 type"

set acluser [cgi_get acluser "-"]
set aclpass [cgi_get aclpass "-"]
set aclpassc [cgi_get aclpassc "-"]
if {$acluser ne "-" && $aclpass ne "-"} {
	if {![string length $acluser]} {
		puts "No username provided."
		exit
	}
	if {$aclpass ne $aclpassc} {
		puts "Passwords do not match."
		exit
	}
	if {[string length $aclpass] < 4} {
		puts "Password is too short (< 4 characters)"
		exit
	}
	puts [$settings addacluser $acluser $aclpass]
	exit
}

set aclact [cgi_get aclact "-"]
if {$aclact ne "-" && $acluser ne "-"} {
	switch $aclact {
		"del" { puts [$settings delacluser $acluser] }
	}
	exit
}

jqplugin form actual iphone-style-checkboxes touchpunch
jscss settings.js
header

[spinner new {
        text "Loading Settings..."
        size "1.2em"
        style "margin: 1em;"
        }] start

puts {
<div id=accordion class=hidden>
}

proc setting_toggle {name attr checked {invert 0} {val 0}} {
	puts -nonewline "
	    <tr>
		<th class=key>$name</th>
		<td><input class=setting_toggle type=checkbox value=yes"
	if {$checked} { puts -nonewline " checked" }
	puts -nonewline " attr=$attr"
	if {$invert} { puts -nonewline " invert=1" }
	if {$val} { puts -nonewline " useval=1" }
	puts -nonewline ">
		<div id=${attr}_output></div>
		</td>
	</tr>
	"
}

puts "
	<h4>General Settings</h4>
	<div><fieldset style=\"display: inline\">
		<legend>
			General Settings
		</legend>
	<table>
"

puts "
	<tr>
	<form class=auto id=hostname method=get action=$env(SCRIPT_NAME)>
		<th class=key>Hostname</th>
		<td><input name=hostname value=\"$hostname\"
		    class=\"text ui-widget-content ui-corner-all\"
		    length=20 maxlength=50>
		    <small>
		    <input id=hostname_submit value=\"change\" type=submit>
		    </small>
		    <div id=hostname_output></div>
		</td>
	</form>
	</tr>
"

setting_toggle "Slide-down toolbar?" "notoolbar" $(!$notoolbar) 1
setting_toggle "Mobile link on main page?" "nomobile" $(!$nomobile) 1
setting_toggle "Help links on main page?" "nohelplinks" $(!$nohelplinks) 1
setting_toggle "Twitter feed ticker on main page?" "notwitfeed" $(!$notwitfeed) 1
setting_toggle "Unwatched count on folders?" "nounwatchedcount" $(!$nounwatchedcount) 1
if {[system pkginst ir]} {
	setting_toggle "Disable channel change confirmation?" \
	    "chanchangenc" $chanchangenc 0
}

puts -nonewline "
	<tr>
	<form class=auto id=autolog method=get action=$env(SCRIPT_NAME)>
		<th class=key>Auto-processing log level</th>
		<td><select id=autolog name=autolog
		    class=\"text ui-widget-content ui-corner-all\">
"
puts "<option value=0"
if {$autolog == 0} { puts " selected" }
puts ">Actions and errors only\n"
puts "<option value=1"
if {$autolog == 1} { puts " selected" }
puts ">Actions, errors and scan information\n"
puts "<option value=2"
if {$autolog == 2} { puts " selected" }
puts ">Debugging information\n"
puts "
		</select>
		<small>
		<input name=autolog value=\"set\" type=submit>
		</small>
		<div id=autolog_output></div>
		</td>
	</form>
	</tr>
"

puts -nonewline "
	<tr>
	<form class=auto id=audiomp3 method=get action=$env(SCRIPT_NAME)>
		<th class=key>Audio extraction type</th>
		<td><select id=audiomp3 name=audiomp3
		    class=\"text ui-widget-content ui-corner-all\">
"
puts "<option value=0"
if {$audiomp3 == 0} { puts " selected" }
puts ">[$settings audiomp3descr 0] - very fast but less compatible.\n"
puts "<option value=1"
if {$audiomp3 == 1} { puts " selected" }
puts ">[$settings audiomp3descr 1] - around 60 times slower.\n"
puts "
		</select>
		<small>
		<input name=audiomp3 value=\"set\" type=submit>
		</small>
		<div id=audiomp3_output></div>
		</td>
	</form>
	</tr>
"

puts "
</table></fieldset></div>
"

puts "
	<h4>Web Interface Settings</h4>
	<div>
	<fieldset style=\"display: inline\">
	<legend> Web Interface Settings </legend>
	<table>
"
setting_toggle "HTTPS web server?" "https" \
    [file exists /mod/etc/webif.pem] 0 1
puts "
	</table>
	</legend></fieldset>
	<br>
	<fieldset style=\"display: inline\">
	<legend> User Access Control </legend>
	<table>
"

set aclusers [$settings aclusers]
if {[llength $aclusers]} {
	puts "<tr><th colspan=5 class=odd>Existing Users</th></tr>"
	foreach user [$settings aclusers] {
		lassign $user user
		puts "<tr><td align=center style=\"font-weight: bold\">
		    $user</td>"
		puts "<th class=key>New password:
	        <input
		  class=\"aclpass text ui-widget-content ui-corner-all\"
		  type=password size=20 maxlength=50><br>"
		puts "Again:
	        <input
		  class=\"aclpassc text ui-widget-content ui-corner-all\"
		  type=password size=20 maxlength=50></td>"
		puts "<th class=key><button class=pwchange>
		    Change</button></td>"
		puts "<th class=key><button class=userdel>
		    Delete User</button></td>"
		puts "</tr>"
	}
	puts "<tr><td colspan=5 id=aclusermod_output>&nbsp;</td></tr>"
	puts "<tr><td colspan=5>&nbsp;</td></tr>"
} else {
	puts "<tr><td colspan=5 class=blood><b>
	    Add a user to enable authentication.</b></td></tr>"
}

puts "<tr><th colspan=5 class=odd>Add New User</th></tr>"
puts "
	<form id=aclnewuser method=get action=$env(SCRIPT_NAME)>
	<tr><th class=key>New User:</th><td>
	    <input
		class=\"text ui-widget-content ui-corner-all\"
		id=acluser name=acluser size=20 maxlength=50></td></tr>
	<tr><th class=key>Password:</th><td>
	    <input type=password
		class=\"text ui-widget-content ui-corner-all\"
		id=aclpass name=aclpass size=20 maxlength=50></td></tr>
	<tr><th class=key>Password (confirm):</th><td>
	    <input type=password
		class=\"text ui-widget-content ui-corner-all\"
		id=aclpassc name=aclpassc size=20 maxlength=50></td></tr>
	<tr><td><input id=aclnewuser_submit value=\"Add User\" type=submit>
	    </td></tr>
	</form>
	</table>
	<div id=aclnewuser_output></div>
	</fieldset>
	</div>
"

puts {
<script type=text/javascript>
$('#aclnewuser').ajaxForm({
	target: '#aclnewuser_output',
	success: function(txt) {
		if (txt.indexOf('Success') >= 0)
			window.location.reload(true);
	}
});

$('button.userdel').click(function(el) {
	var user = $('td:first', $(this).parents('tr')).text().trim();
	$('#aclusermod_output').load(
	    '/settings/settings.jim?aclact=del&acluser=' +
	    encodeURIComponent(user), function(txt) {
		if (txt.indexOf('Success') >= 0)
			window.location.reload(true);
	});
});

$('button.pwchange').click(function(el) {
	var tr = $(this).parents('tr');
	var user = $('td:first', $(tr)).text().trim();
	var pass = $(tr).find('input.aclpass').val();
	var passc = $(tr).find('input.aclpassc').val();
	$('#aclusermod_output').load('/settings/settings.jim?' +
	    'acluser=' + encodeURIComponent(user) + '&' +
	    'aclpass=' + encodeURIComponent(pass) + '&' +
	    'aclpassc=' + encodeURIComponent(passc));
});
</script>
}


puts "
<h4>EPG Settings</h4>
<div><fieldset style=\"display: inline\">
	<legend>
		EPG Settings
	</legend>
<table>
"

puts "
	<tr>
	<form class=auto id=epg_style method=get action=$env(SCRIPT_NAME)>
		<th class=key>Default Now/Next style</th>
		<td><select id=epg_style name=epg_style
		    class=\"text ui-widget-content ui-corner-all\">
"
puts "<option value=standard"
if {$epg_style ne "grid"} { puts " selected" }
puts ">Standard\n"
puts "<option value=grid"
if {$epg_style eq "grid"} { puts " selected" }
puts ">Grid\n"
puts "
		</select>
		<small>
		<input name=epg_style value=\"set\" type=submit>
		</small>
		<div id=epg_style_output></div>
		</td>
	</form>
	</tr>
"

puts "
	<tr>
	<form class=auto id=service_style method=get action=$env(SCRIPT_NAME)>
		<th class=key>Default Single-channel style</th>
		<td><select id=service_style name=service_style
		    class=\"text ui-widget-content ui-corner-all\">
"
puts "<option value=standard"
if {$service_style eq "standard"} { puts " selected" }
puts ">Standard\n"
puts "<option value=grid"
if {$service_style ne "standard"} { puts " selected" }
puts ">Grid\n"
puts "
		</select>
		<small>
		<input name=service_style value=\"set\" type=submit>
		</small>
		<div id=service_style_output></div>
		</td>
	</form>
	</tr>
"

puts "
	<tr>
	<form class=auto id=channel_group method=get action=$env(SCRIPT_NAME)>
		<th class=key>Channel Group for EPG</th>
		<td><select id=channel_group name=channel_group
		    class=\"text ui-widget-content ui-corner-all\">
"

set i 0
puts "<option value=0>-- None --"
foreach grp [$settings channel_groups] {
	incr i
	puts -nonewline "<option value=$i"
	if {$channel_group == $i} {
		puts -nonewline " selected"
	}
	puts ">$grp"
}

puts "
		</select>
		<small>
		<input name=channel_group value=\"set\" type=submit>
		</small>
		<div id=channel_group_output></div>
		</td>
	</form>
	</tr>
"

puts "
	<tr>
	<form class=auto id=xepghours method=get action=$env(SCRIPT_NAME)>
		<th class=key>Grid-style EPG Hours</th>
		<td><select id=xepghours name=xepghours
		    class=\"text ui-widget-content ui-corner-all\">
"

foreach xehopt {2 3 4 5 6} {
	puts -nonewline "<option value=$xehopt"
	if {$xehopt == $xepghours} {
		puts -nonewline " selected"
	}
	puts ">$xehopt hours"
}

puts "
		</select>
		<small>
		<input name=xepghours value=\"set\" type=submit>
		</small>
		<div id=xepghours_output></div>
		</td>
	</form>
	</tr>
"

setting_toggle "De-duplicate genre search results?" genrededup $genrededup

puts "
	</table>
	</fieldset></div>
"

#puts "
#	<fieldset style=\"display: inline\">
#	<legend> Email Settings </legend>
#	<table>
#"
#
#puts "
#	<tr>
#	<form class=auto id=smtp_server method=get action=$env(SCRIPT_NAME)>
#		<th class=key>SMTP Server for outbound email</th>
#		<td><input name=smtp_server value=\"$smtp_server\"
#		    class=\"text ui-widget-content ui-corner-all\"
#		    length=20 maxlength=50>
#		    <small>
#		    <input id=smtp_server_submit value=\"change\" type=submit>
#		    </small>
#		    <div id=smtp_server_output></div>
#		</td>
#	</form>
#	</tr>
#"
#
#puts "
#	</table>
#	</fieldset>
#	<br><br>
#"

puts -nonewline "
	<h4>Advanced Settings</h4>
	<div>
	<fieldset style=\"display: inline\">
	<legend> Advanced Settings </legend>
	<table>
"
setting_toggle "Show development and advanced packages?" "pkgdev" $pkgdev

if {[system modversion 1] >= 214} {
	setting_toggle "Expert mode telnet server?" "xtelnet" \
	    [file exists /mod/boot/xtelnet] 0 1
}

puts "
	</table>
	</fieldset>
	</div>
"

set hook settings
foreach plugin [lsort [glob -nocomplain /mod/webif/plugin/*]] {
	if {[file isfile "$plugin/$hook.hook"]} {
		puts "<h4>Settings for <i>[file tail $plugin]</i> package</h4>"
		puts "<div class=pluginsettings>"
		catch {source "$plugin/$hook.hook"}
		puts "</div>"
	} 
}

puts "</div>"

footer

