#!/usr/bin/perl -w
# Quest, a computer role playing game system
# Copyright (C) 2002 Willem Robert van Hage, details in the COPYING file.

use strict;
use Getopt::Long;
use IO::Socket;
use Net::hostent;
use com;
use xml;

my $help = 0;

my $usage = <<END_OF_USAGE;
Usage: $0 [OPTIONS]...
Starts the Quest server with the given parameters.
  -p PORT, --port PORT       the port number of the server (default = 4242)
  -?,      --help            display this help and exit

Report bugs to <wrvh\@xs4all.nl>.
END_OF_USAGE

GetOptions('help|?' => \$help,
           'port=i' => \(my $port = 4242)) or die "can't parse options";

if ($help) { print $usage; exit }

my ($server,$client);
$server = IO::Socket::INET->new(Proto     => 'tcp',    
                                LocalPort => $port,
                                Listen    => SOMAXCONN, 
								Reuse     => 1) or die "can't start server";

print "server $0 accepting clients at port $port\n";

while ($client = $server->accept) {
	my $hostinfo = gethostbyaddr $client->peeraddr;
	$client->autoflush(1);
	printf "accepting [%s]\n", $hostinfo->name;

	my $request = com::recv_string($client);
	my $req = xml::parse_request($request);
	if ($req->{type} eq 'file') {
		my $path = $req->{path} . "/" . $req->{name};
		if (-e $path) {
			printf "sending   [$path] to [%s]\n", $hostinfo->name;
			com::send_file($client,$path) or 
			com::send_string($client,xml::error("$path can't be opened"));
		} else { 
			printf "error to  [%s] [$path doesn't exist]\n", $hostinfo->name;
			com::send_string($client,xml::error("$path doesn't exist"));
		}
	}
	printf "closing   [%s]\n", $hostinfo->name;
	close $client
}

