<style>
.cbi-input-select {
    width: auto !important;
}
</style>

<fieldset class="cbi-section">
	<table width="100%">
	  <tr><td width="100%" colspan="6">
	    <p align="center" id="update_tip">
	  		<b><%:Note: if the update fails, you can manually download and upload%></b>
	  	</p>
	  </td></tr>
	  <tr><td width="16.6%" align="right"><%:Compiled Version%></td>
	  	<td width="16.6%" align="left">
			<select class="cbi-input-select" name="CORE_VERSION" id="CORE_VERSION">
	  			<option value="linux-386"><%:linux-386%></option>
				<option value="linux-amd64-v1"><%:linux-amd64-v1(x86-64)%></option>
				<option value="linux-amd64-v2"><%:linux-amd64-v2(x86-64)%></option>
				<option value="linux-amd64-v3"><%:linux-amd64-v3(x86-64)%></option>
				<option value="linux-armv5"><%:linux-armv5%></option>
				<option value="linux-armv6"><%:linux-armv6%></option>
				<option value="linux-armv7"><%:linux-armv7%></option>
				<option value="linux-arm64"><%:linux-arm64(armv8)%></option>
				<option value="linux-loong64-abi1"><%:linux-loong64-abi1%></option>
				<option value="linux-loong64-abi2"><%:linux-loong64-abi2%></option>
				<option value="linux-riscv64"><%:linux-riscv64%></option>
				<option value="linux-s390x"><%:linux-s390x%></option>
				<option value="linux-mips-hardfloat"><%:linux-mips-hardfloat%></option>
				<option value="linux-mips-softfloat"><%:linux-mips-softfloat%></option>
				<option value="linux-mips64"><%:linux-mips64%></option>
				<option value="linux-mips64le"><%:linux-mips64le%></option>
				<option value="linux-mipsle-softfloat"><%:linux-mipsle-softfloat%></option>
				<option value="linux-mipsle-hardfloat"><%:linux-mipsle-hardfloat%></option>
				<option value="0"><%:Not Set%></option>
	  		</select>
		</td>
	  	<td width="16.6%" align="right"><%:Release Branch%></td>
	  	<td width="16.6%" align="left"><select class="cbi-input-select" name="RELEASE_BRANCH" id="RELEASE_BRANCH">
	  		<option value="master">Master</option>
			<option value="dev">Developer</option>
	  	</select></td>
		<td width="16.6%" align="right"><%:Smart Core%> <a href="javascript:void(0);" onclick="window.open('https://github.com/vernesong/mihomo/releases', '_blank');" style="color: #0066cc; text-decoration: none;" title="<%:View core infos that support smart group%>"> (?)</a></td>
	  	<td width="16.6%" align="left"><select class="cbi-input-select" name="SMART_ENABLE" id="SMART_ENABLE">
	  		<option value="0"><%:Disabled%></option>
			<option value="1"><%:Enable%></option>
	  	</select></td>
	  	</tr>
	</table>
</fieldset>
<fieldset class="cbi-section">
	<table width="100%">
		<tr><td width="100%" colspan="4">
	    <p align="center">
	  		<b><%:Core Update%></b>
	  	</p>
	  	</td></tr>
	  	<tr><td width="100%" colspan="4">
		<tr>
			<td width="25%"><%:CPU Architecture%></td><td width="25%" align="left" id="CPU_MODEL"><%:Collecting data...%></td>
			<td width="25%"><%:Last Check Update%></td><td width="25%" align="left" id="CHECKTIME"><%:Collecting data...%></td>
		</tr>
	  	<tr><td width="100%" colspan="4">
	    <p align="center">
	  		<b><%:Core path:%>/etc/openclash/core/clash_meta</b>
	  	</p>
	  	</td></tr>
		<tr><td width="25%">[Meta] <%:Current Core%></td><td width="25%" align="left" id="CORE_META_CV"><%:Collecting data...%></td><td width="25%">[Meta] <%:Latest Core%></td><td width="25%" align="left" id="CORE_META_LV"><%:Collecting data...%></td></tr>
		<tr><td width="25%"><%:Update Core%></td><td width="25%" align="left" id="core_meta_up"><%:Collecting data...%></td><td width="25%"><%:Download Latest Core%></td><td width="25%" align="left" id="ma_core_meta_up"><%:Collecting data...%></td></tr>
	</table>
</fieldset>
<fieldset class="cbi-section">
	<table width="100%">
		<tr><td width="100%" colspan="4">
	    <p align="center">
	  		<b><%:Client Update%></b>
	  	</p>
	  	</td></tr>
		<tr><td width="25%"><%:Current Client%></td><td width="25%" align="left" id="OP_CV"><%:Collecting data...%></td><td width="25%"><%:Latest Client%></td><td width="25%" align="left" id="OP_LV"><%:Collecting data...%></td></tr>
	  	<tr><td width="25%"><%:Update Client%></td><td width="25%" align="left" id="op_up"><%:Collecting data...%></td><td width="25%"><%:Download Latest Client%></td><td width="25%" align="left" id="ma_op_up"><%:Collecting data...%></td></tr>
	</table>
</fieldset>
<fieldset class="cbi-section">
	<table width="100%">
	  <tr>
	  	<td width="33%">
	  	   <p align="center" id="restore">
	  		   <%:Collecting data...%>
	  	   </p>
	  	</td>
	  	<td width="33%">
	  	   <p align="center" id="remove_core">
	  		   <%:Collecting data...%>
	  	   </p>
	  	</td>
		  <td width="33%">
			<p align="center" id="one_key_update_cdn">
				<%:Collecting data...%>
			</p>
	   </td>
	  </tr>
	</table>
</fieldset>
<fieldset class="cbi-section">
	<table width="100%">
		<tr><td width="100%" colspan="4">
	    <p align="center">
	  		<b><%:Backup Section%></b>
	  	</p>
		</td></tr>
		<tr>
	  	<td width="25%">
	  	   <p align="center" id="backup">
	  		   <%:Collecting data...%>
	  	   </p>
	  	</td>
	  	<td width="25%">
	  	   <p align="center" id="backup_ex_core">
	  		   <%:Collecting data...%>
	  	   </p>
	  	</td>
	  	<td width="25%">
	  	   <p align="center" id="backup_core_only">
	  		   <%:Collecting data...%>
	  	   </p>
	  	</td>
		</tr>
		<tr>
	  	<td width="25%">
	  	   <p align="center" id="backup_config_only">
	  		   <%:Collecting data...%>
	  	   </p>
	  	</td>
	  	<td width="25%">
	  	   <p align="center" id="backup_rule_only">
	  		   <%:Collecting data...%>
	  	   </p>
	  	</td>
	  	<td width="25%">
	  	   <p align="center" id="backup_proxy_only">
	  		   <%:Collecting data...%>
	  	   </p>
	  	</td>
		</tr>
	</table>
</fieldset>

<script type="text/javascript">//<![CDATA[
	var core_version = document.getElementById('CORE_VERSION');
 	var checktime = document.getElementById('CHECKTIME');
	var cpu_model = document.getElementById('CPU_MODEL');
	var core_meta_cv = document.getElementById('CORE_META_CV');
	var core_meta_lv = document.getElementById('CORE_META_LV');
	var op_cv = document.getElementById('OP_CV');
	var op_lv = document.getElementById('OP_LV');
	var core_meta_up = document.getElementById('core_meta_up');
	var op_up = document.getElementById('op_up');
	var update_tip = document.getElementById('update_tip');
	var ma_core_meta_up = document.getElementById('ma_core_meta_up');
	var ma_op_up = document.getElementById('ma_op_up');
	var restore = document.getElementById('restore');
	var backup = document.getElementById('backup');
	var backup_ex_core = document.getElementById('backup_ex_core');
	var backup_core_only = document.getElementById('backup_core_only');
	var backup_config_only = document.getElementById('backup_config_only');
	var backup_rule_only = document.getElementById('backup_rule_only');
	var backup_proxy_only = document.getElementById('backup_proxy_only');
	var one_key_update_cdn = document.getElementById('one_key_update_cdn');
	var remove_core = document.getElementById('remove_core');
	var release_branch = document.getElementById('RELEASE_BRANCH');
	var smart_enable = document.getElementById('SMART_ENABLE');
	core_meta_up.innerHTML = '<input type="button" class="btn cbi-button cbi-button-reload" value="<%:Check And Update%>" onclick="return core_update(this,\'Meta\')"/>';
	op_up.innerHTML = '<input type="button" class="btn cbi-button cbi-button-reload" value="<%:Check And Update%>" onclick="return op_update(this)"/>';
	ma_core_meta_up.innerHTML = '<input type="button" class="btn cbi-button cbi-button-reload" value="<%:Download%>" onclick="return ma_core_update(this,\'Meta\')"/>';
	ma_op_up.innerHTML = '<input type="button" class="btn cbi-button cbi-button-reload" value="<%:Download%>" onclick="return ma_op_update(this)"/>';
	restore.innerHTML = '<input type="button" class="btn cbi-button cbi-button-reset" value="<%:Restore Default Config%>" onclick="return restore_config(this)"/>';
	one_key_update_cdn.innerHTML = '<input type="button" class="btn cbi-button cbi-button-reset" value="<%:Check Update%>" onclick="return all_one_key_update_cdn(this)"/>';
	remove_core.innerHTML = '<input type="button" class="btn cbi-button cbi-button-reset" value="<%:Remove Core%>" onclick="return remove_all_core(this)"/>';
	backup.innerHTML = '<input type="button" class="btn cbi-button cbi-button-reset" value="<%:Backup OpenClash%>" onclick="return backup_all_file(this)"/>';
	backup_ex_core.innerHTML = '<input type="button" class="btn cbi-button cbi-button-reset" value="<%:Backup Exclude Cores%>" onclick="return backup_no_core(this)"/>';
	backup_core_only.innerHTML = '<input type="button" class="btn cbi-button cbi-button-reset" value="<%:Backup Core%>" onclick="return backup_only_core(this)"/>';
	backup_config_only.innerHTML = '<input type="button" class="btn cbi-button cbi-button-reset" value="<%:Backup Config%>" onclick="return backup_only_config(this)"/>';
	backup_rule_only.innerHTML = '<input type="button" class="btn cbi-button cbi-button-reset" value="<%:Backup Rule Provider%>" onclick="return backup_only_rule(this)"/>';
	backup_proxy_only.innerHTML = '<input type="button" class="btn cbi-button cbi-button-reset" value="<%:Backup Proxy Provider%>" onclick="return backup_only_proxy(this)"/>';

	XHR.get('<%=luci.dispatcher.build_url("admin", "services", "openclash", "update_info")%>', null, function(x, status) {
		if ( x && x.status == 200 ) {
			if ( status.corever && status.corever != "0" && status.corever != "" ) {
		  		core_version.value = status.corever;
			}
			else {
		  		core_version.value = "0";
			}
			if ( status.release_branch && status.release_branch != "" ) {
		  		release_branch.value = status.release_branch;
			}
			else {
		  		release_branch.value = "master";
			}
			if ( status.smart_enable && status.smart_enable != "" ) {
				smart_enable.value = status.smart_enable;
			}
			else {
				smart_enable.value = "0";
			}
		}
		else {
			core_version.value = "0";
			release_branch.value = "master";
			smart_enable.value = "0";
		}
	});

	XHR.poll(300, '<%=luci.dispatcher.build_url("admin", "services", "openclash", "get_last_version")%>', null, function(x, status) {
	});
	
	function updateStatus(x, status) {
        if ( x && x.status == 200 ) {
            cpu_model.innerHTML = status.coremodel ? "<b style=color:green>"+status.coremodel+"</b>" : "<b style=color:red><%:Model Not Found%></b>";
            if ( status.upchecktime != "1" ) {
                checktime.innerHTML = "<b style=color:green>"+status.upchecktime+"</b>";
            }
            else {
                checktime.innerHTML = "<b style=color:red><%:Check Failed%></b>";
            }
            if ( status.coremetacv == "0" ) {
                core_meta_cv.innerHTML = "<b style=color:red><%:Unknown%></b>";
            }
            else {
                core_meta_cv.innerHTML = "<b style=color:green>"+status.coremetacv+"</b>";
            }
            var coremetalvis = status.corelv;
            if (coremetalvis != status.coremetacv && coremetalvis != "" && coremetalvis != "loading...") {
               core_meta_lv.innerHTML = "<b style=color:green>"+coremetalvis+" <%:<New>%></b>";
            }
            else if (coremetalvis != "" && coremetalvis == status.coremetacv && coremetalvis != "loading...") {
               core_meta_lv.innerHTML = "<b style=color:green>"+coremetalvis+"</b>";
            }
            else if (coremetalvis == "loading...") {
               core_meta_lv.innerHTML = "<b style=color:green><%:Getting Last Version...%></b>";
            }
            else {
               core_meta_lv.innerHTML = "<b style=color:red><%:Unknown%></b>";
            }
            var oplv = status.oplv;
            op_cv.innerHTML = status.opcv != "0" ? "<b style=color:green>"+status.opcv+"</b>" : "<b style=color:red><%:Unknown%></b>";
            if (oplv != "" && oplv != "loading..." && status.opcv != "0") {
                function compareVersions(v1, v2) {
                    var ver1 = v1.replace(/^v/, '').split('.');
                    var ver2 = v2.replace(/^v/, '').split('.');
                    
                    var maxLen = Math.max(ver1.length, ver2.length);
                    while (ver1.length < maxLen) ver1.push('0');
                    while (ver2.length < maxLen) ver2.push('0');
                    
                    for (var i = 0; i < maxLen; i++) {
                        var num1 = parseInt(ver1[i], 10);
                        var num2 = parseInt(ver2[i], 10);
                        if (num1 > num2) return 1;
                        if (num1 < num2) return -1;
                    }
                    return 0;
                }
                
                if (compareVersions(oplv, status.opcv) > 0) {
                    op_lv.innerHTML = "<b style=color:green>"+oplv+" <%:<New>%></b>";
                } else {
                    op_lv.innerHTML = "<b style=color:green>"+oplv+"</b>";
                }
            }
            else if (oplv != "" && oplv != "loading...") {
                op_lv.innerHTML = "<b style=color:green>"+oplv+"</b>";
            }
            else if (oplv == "loading...") {
                op_lv.innerHTML = "<b style=color:green><%:Getting Last Version...%></b>";
            }
            else {
                op_lv.innerHTML = "<b style=color:red><%:Unknown%></b>";
            }
        }
    }

    XHR.get('<%=luci.dispatcher.build_url("admin", "services", "openclash", "update")%>', null, updateStatus);
    
    XHR.poll(10, '<%=luci.dispatcher.build_url("admin", "services", "openclash", "update")%>', null, updateStatus);

	function handleStartLog(x, status) {
        if ( x && x.status == 200 ) {
            if ( status.startlog == "\n" || status.startlog == "" || status.startlog == "##FINISH##\n" ) {
                var rdmdl = Math.floor(Math.random()*3)+1;
                if(rdmdl == 1) {
                    update_tip.innerHTML = '<b><font><%:Note: if the update fails, you can manually download and upload%></font></b>';
                }
                else if(rdmdl == 2) {
                    update_tip.innerHTML = '<b><font><%:Note: the client may not support update, because the firmware with squashfs format will not release flash space after updating%></font></b>';
                }
                else if(rdmdl == 3) {
                    update_tip.innerHTML = '<b><font><%:Note: options will auto-save when you click to update or download%></font></b>';
                }
            }
            else if ( status.startlog.match("level=fatal") || status.startlog.indexOf("FTL [Config]") != "-1" ) {
                XHR.get('<%=luci.dispatcher.build_url("admin", "services", "openclash", "del_start_log")%>', null, function(x) {});
                if ( status.startlog.match("level=fatal") ) {
                    alert('<%:OpenClash Start Failed%> :\n\n' + status.startlog.split('msg=')[1]);
                }
                else {
                    alert('<%:OpenClash Start Failed%> :\n\n' + status.startlog.split('FTL [Config] ')[1]);
                }
            }
            else if ( status.startlog != "\n" && status.startlog != "" && status.startlog != "##FINISH##\n" ) {
                if ( status.startlog.match("Tip:") || status.startlog.match("提示：")) {
                    update_tip.innerHTML = '<b style=color:#ff6f00>'+status.startlog+'</b>';
                }
                else if ( status.startlog.match("Error:") || status.startlog.match("错误：")) {
                    update_tip.innerHTML = '<b style=color:#FF0000>'+status.startlog+'</b>';
                }
                else if ( status.startlog.match("Warning:") || status.startlog.match("警告：")) {
                    update_tip.innerHTML = '<b style=color:#ff00bb>'+status.startlog+'</b>';
                }
                else if ( status.startlog.match("Watchdog:") || status.startlog.match("守护程序：")) {
                    update_tip.innerHTML = '<b style=color:#b300ff>'+status.startlog+'</b>';
                }
                else {
                    update_tip.innerHTML = '<b style=color:green>'+status.startlog+'</b>';
                }
            }
        }
    }

    XHR.poll(3, '<%=luci.dispatcher.build_url("admin", "services", "openclash", "startlog")%>', null, handleStartLog);
	
	function core_update(btn,type)
    {
    	var v = core_version.value;
    	var r = release_branch.value;
		var s = smart_enable.value;
		XHR.get('<%=luci.dispatcher.build_url("admin", "services", "openclash", "save_corever_branch")%>', {core_ver: v, release_branch: r, smart_enable: s}, function(x, status) {
			if (x && x.status == 200) {
				XHR.get('<%=luci.dispatcher.build_url("admin", "services", "openclash", "coreupdate")%>', {core_type: type}, function(x, status) {
					btn.value    = '<%:Check And Update%>';
					btn.disabled = false;
					return false;
				});
			}
		});
    }

	function op_update(btn)
    {
        var v = core_version.value;
    	var r = release_branch.value;
		var s = smart_enable.value;
		XHR.get('<%=luci.dispatcher.build_url("admin", "services", "openclash", "save_corever_branch")%>', {core_ver: v, release_branch: r, smart_enable: s}, function(x, status) {
			if (x && x.status == 200) {
				XHR.get('<%=luci.dispatcher.build_url("admin", "services", "openclash", "opupdate")%>', null, function(x, status) {
					btn.value    = '<%:Check And Update%>';
					btn.disabled = false;
					return false;
				});
			}
		});
    }
    
    function ma_core_update(btn,type)
    {
    	var v = core_version.value;
		var r = release_branch.value;
		var s = smart_enable.value;
		XHR.get('<%=luci.dispatcher.build_url("admin", "services", "openclash", "save_corever_branch")%>', {core_ver: v, release_branch: r, smart_enable: s}, function(x, status) {
		if (x && x.status == 200) {
			btn.value    = '<%:Download%>';
			btn.disabled = false;
			XHR.get('<%=luci.dispatcher.build_url("admin", "services", "openclash", "update_ma")%>', status.corever, function(x, status) {
			if ( x && x.status == 200 ) {
				if ( status.corever != "0" ) {
					if (type == "Meta") {
						if (s == "1") {
							url4='https://raw.githubusercontent.com/vernesong/OpenClash/core/'+r+'/smart/clash-'+status.corever+'.tar.gz';
							window.location.href=url4;
						}
						else {
							url4='https://raw.githubusercontent.com/vernesong/OpenClash/core/'+r+'/meta/clash-'+status.corever+'.tar.gz';
							window.location.href=url4;
						}
					}
				}
				else {
					alert('<%:No Compiled Version is Selected, Please Select on The Top and Try Again!%>')
				}
			}
       		});
        return false;
    	}
      });
    }
    
    function ma_op_update(btn)
    {
        btn.value    = '<%:Download%>';
        btn.disabled = false;
        var v = core_version.value;
		var r = release_branch.value;
		var s = smart_enable.value;
		XHR.get('<%=luci.dispatcher.build_url("admin", "services", "openclash", "save_corever_branch")%>', {core_ver: v, release_branch: r, smart_enable: s}, function(x, status) {
			if (x && x.status == 200) {
				XHR.get('<%=luci.dispatcher.build_url("admin", "services", "openclash", "update_ma")%>', status.oplv, function(x, status) {
					if ( x && x.status == 200 ) {
						var oplv = status.oplv.substring(status.oplv.indexOf("v") + 1);
						if ( oplv != "" && oplv != "loading..." ) {
							if (status.pkg_type == "apk") {
								url2='https://raw.githubusercontent.com/vernesong/OpenClash/package/'+r+'/luci-app-openclash-'+oplv+'.apk';
							}
							else {
								url2='https://raw.githubusercontent.com/vernesong/OpenClash/package/'+r+'/luci-app-openclash_'+oplv+'_all.ipk';
							}
							window.location.href=url2;
						}
						else {
							alert('<%:Failed to get the latest version. Please try again later!%>')
						}
					}
				});
			}
        });
        return false; 
    }
    
    function remove_all_core(btn)
    {
        btn.value    = '<%:Remove Core%>';
        btn.disabled = true;
        var r = confirm("<%:Are you sure want to remove all core files?%>")
        if (r == true) {
        XHR.get('<%=luci.dispatcher.build_url("admin", "services", "openclash", "remove_all_core")%>', null, function(x, status) {
        	if ( x && x.status == 200 ) {
        		alert('<%:Remove succeeded!%>')
        	}
          	else {
            alert('<%:Remove failed!%>')
           }
        });
        } else {
        }
        btn.disabled = false;
        return false; 
    }
    
    function backup_all_file(btn)
    {
		btn.value    = '<%:Backup OpenClash%>';
		btn.disabled = true;
		window.location.href='<%="backup"%>';
		btn.disabled = false;
		return false; 
    }

    function backup_no_core(btn)
    {
		btn.value    = '<%:Backup Exclude Cores%>';
		btn.disabled = true;
		window.location.href='<%="backup_ex_core"%>';
		btn.disabled = false;
		return false; 
    }

    function backup_only_core(btn)
    {
		btn.value    = '<%:Backup Core%>';
		btn.disabled = true;
		window.location.href='<%="backup_only_core"%>';
		btn.disabled = false;
		return false; 
    }

    function backup_only_config(btn)
    {
		btn.value    = '<%:Backup Config%>';
		btn.disabled = true;
		window.location.href='<%="backup_only_config"%>';
		btn.disabled = false;
		return false; 
    }

    function backup_only_rule(btn)
    {
		btn.value    = '<%:Backup Rule Provider%>';
		btn.disabled = true;
		window.location.href='<%="backup_only_rule"%>';
		btn.disabled = false;
		return false; 
    }

    function backup_only_proxy(btn)
    {
		btn.value    = '<%:Backup Proxy Provider%>';
		btn.disabled = true;
		window.location.href='<%="backup_only_proxy"%>';
		btn.disabled = false;
		return false; 
    }

	function all_one_key_update_cdn(btn)
    {
    	var v = core_version.value;
		var r = release_branch.value;
		var s = smart_enable.value;
		XHR.get('<%=luci.dispatcher.build_url("admin", "services", "openclash", "save_corever_branch")%>', {core_ver: v, release_branch: r, smart_enable: s}, function(x, status) {
			if (x && x.status == 200) {
				btn.value    = '<%:Check Update%>';
				btn.disabled = false;
				return select_git_cdn("one_key_update");
			}
		});
    }

//]]></script>
