<?php
// Let's respect users who had set the Web password
// and reuse Siglent's login machinery.
session_start();
 
$passwd = `cat /usr/bin/siglent/usr/webserver_password`;
if($passwd != null && !isset($_SESSION['logged_in'])) {
	$_SESSION['url'] = "cli.php";
	header('Location: login.php');
	exit();
}

$cmd_prompt = '$ ';
if (getmyuid() === 0)
	$cmd_prompt = '# ';

$cmd = '';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
	if (isset($_POST['cmd']))
		$cmd = $_POST['cmd'];
	if (isset($_POST['_cwd']))
		chdir($_POST['_cwd']);
}

$builtin_result = '';
$args = preg_split("/\s+/", $cmd, 2, PREG_SPLIT_NO_EMPTY);
if (count($args) != 0) {
	 if ($args[0] == 'cd') {
		if (count($args) <= 1)
			;
		else if(is_dir($args[1])) {
			if (!chdir($args[1]))
				$builtin_result = "$args[1]: failed to change directory.";
		} else
			$builtin_result = "$args[1]: no such directory.";
		$cmd = '';
	}
}

$cwd = getcwd();
if ($cwd != "/")
	$cwd .= '/';
?>

<!DOCTYPE html>
<html>
<head>
<title>Siglent CLI console</title>
<style>
.cmd_output {
	background: #f8f8f8;
	border: 1px solid #d0d0d0;
	padding: 0.2em;
}
</style>
<script language="JavaScript">
function onLoad() {
	var id = document.getElementById("cmd");
	if (id)
		id.focus();
}
</script>
</head>
<body onLoad='onLoad(); return true;'>
<h1>Siglent CLI console</h1>
<p>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<?php echo $cwd, $cmd_prompt; ?>
<input type="text" name="cmd" id="cmd" value="<?php echo htmlspecialchars($cmd); ?>" />
<input type="hidden" name="_cwd" value="<?php echo htmlspecialchars($cwd); ?>" />
<input type="submit" value="Go" />
</form>
<?php
if ($cmd != '') {
	exec(escapeshellcmd($cmd), $output, $retval);
	echo "<p>Command status is $retval.";
	if (empty($output)) {
		echo '  The output is empty.';
	} else {
		echo '  Output follows.';
		echo '<pre class="cmd_output">';
		foreach ($output as $line)
			echo htmlspecialchars($line), "\n";
		echo '</pre>';
	}
} else if ($builtin_result != '') {
	echo '<p>', htmlspecialchars($builtin_result);
}
?>
</body>
</html>
