<?php
error_reporting(0);

$type   = trim($_SERVER['argv'][1]);
$server = trim($_SERVER['argv'][2]);

$server_ip   = isset($_SERVER['argv'][3]) ? trim($_SERVER['argv'][3])   : '127.0.0.1';
$server_port = isset($_SERVER['argv'][3]) ? intval($_SERVER['argv'][4]) : 80;

// var_dump($_SERVER['argv']);

$fp  = fsockopen($server_ip, $server_port, $errno, $errstr, 1);
$out = "GET / HTTP/1.1\r\nHost: $server_ip\r\nConnection: Close\r\n\r\n";

if ($fp) {
	echo "Your port $server_ip:$server_port is actually used by :\n\t";
	
	fwrite($fp, $out);
	while (!feof($fp)) {
		$line = fgets($fp, 128);
		if(false !== stripos($line, 'Server:')){
			echo $line;
			$gotInfo = 1;
		}
	}
	fclose($fp);

	if ($gotInfo != 1) {
		echo 'Information not available (might be Skype).';
	}

	if ('install' === $type) {
		echo "\n\tCannot install the {$server} service, please stop this application and try again.";
		echo "\n\n\tPress Enter to exit...";
		trim(fgets(STDIN));
	} else {
		echo "\n\n\tPress Enter to exit...";
		trim(fgets(STDIN));
	}
} else {
	if ('install' === $type) {
		echo "Your port $server_ip:$server_port is available, {$server} install will proceed.";
		echo "\n\n\tPress Enter to exit...";
		// trim(fgets(STDIN));
	} else {
		echo "Your port $server_ip:$server_port is not actually used.";
		echo "\n\n\tPress Enter to exit...";
		trim(fgets(STDIN));
	}
}

exit(0);