#!/usr/bin/perl
#
# A CGI script to shutdown a BKGo server on a certain port;
# no customization is needed.
#
# Note:  this script retrieves its two form-arguments using
#        the CGI POST method, so that the password isn't displayed
#        in the URL!

use IO::Socket;

# ---------------------------------------------------------------

# Fetch the input-stream arguments to this script via POST method
$servername = $ENV{'SERVER_NAME'};
$size_of_form_info = $ENV{'CONTENT_LENGTH'};
read(STDIN, $form_info, $size_of_form_info);
@key_value_pairs = split(/&/, $form_info);
foreach $key_value (@key_value_pairs) {
    ($key, $value) = split(/=/, $key_value);
    $value =~ tr/+/ /;
    $value =~ s/%([\dA-Fa-f][\dA-Fa-f])/pack ("C", hex ($1))/eg;
    if ($key eq "prt") {
	$port = $value;
    }
    if ($key eq "passwd") {
	$password = $value;
    }
}


print "Content-type: text/html", "\n\n";
print "<title>BKGo Web System</title>";
print "<h1>Shutting down BKGo server...</h1>";

# Connect and do the protocol for a shutdown

if ($socket = IO::Socket::INET->new(PeerAddr => $servername,
				    PeerPort => $port,
				    Proto    => "tcp",
				    Type     => SOCK_STREAM))
{
    $serverver = <$socket>;
    print $socket "Perl shutdown script\n";
    $ok = <$socket>;

    print $socket "shutdown\n";
    $reply = <$socket>;

    if ($reply =~ /terminated/) {
	print "<b>Success</b>: Server on port ".$port." has been terminated.";
	close($socket);
	print "<p>Click <a href=\"list_servers.pl\">here</a> to return to the
           list of running GoServers.";

	exit;
    }

    if ($reply =~ /GimmePassword/) {
	print $socket "Password: ".$password."\n";
	$reply = <$socket>;

	if ($reply =~ /terminated/) {
	    print "<b>Success</b>: Server on port ".$port." has been terminated.";
	    close($socket);
	    print "<p>Click <a href=\"list_servers.pl\">here</a> to return 
                    to the list of running GoServers.";
	    exit;
	}
	else {
	    print "<b>Error</b>: Unexpected server response: '".$reply."'";
	    close($socket);
	    print "<p>Click <a href=\"list_servers.pl\">here</a> to return 
                    to the list of running GoServers.";
	    exit;
	}
    }
    
    else {
	print "<b>Error</b>: Unexpected server response: '".$reply."'";
	close($socket);
	print "<p>Click <a href=\"list_servers.pl\">here</a> to return 
                    to the list of running GoServers.";
	exit;
    }
}

else # couldn't open socket 
{
    print "<b>Error</b>: There's no server running on port ".$port."!\n";
    close($socket);
    print "<p>Click <a href=\"list_servers.pl\">here</a> to return 
                    to the list of running GoServers.";
    exit;
}




