#!/usr/bin/perl

#use IO::Socket::INET;
use IO::Socket;
use IO::Select;

$SIG{PIPE} = 'IGNORE';

# use URI::Escape; # you'll need this later i guess ...

$verb = 5;  # verbosity for console messages

$main = new IO::Socket::INET (  #LocalHost => 'stray.ch',
                              LocalPort => 4444,
                              Listen    => 5,
                              Proto     => 'tcp', 
                              Reuse     => 1 ) || die $!;



$zero = chr(0);
$/ = $zero;
$\ = $zero;
$| = 1;


# Initialise IO::Select ------------------------------------------------


$handles = new IO::Select();
$handles->add($main);

print "Starting listening cycle\n" if ($verb > 1);


LISTEN: while (1) {
   ($pending) = IO::Select->select($handles, undef, undef, 60);
   foreach $sock (@$pending) {

     if ($sock == $main) {
        $num++;
        print "Got new connection: $num from ".$sock->sockhost()."\n" if ($verb > 2); 
        my $newsock = $sock->accept();
        $newsock->autoflush();
        $number{$newsock} = $num;
        $x{$newsock} = 100;
        $y{$newsock} = 100;
        $color{$newsock} = int(rand(20));
        $handles->add($newsock);

        foreach $client ($handles->handles) {
          print $client qq|<create user="user$number{$newsock}" x="$x{$newsock}" y="$y{$newsock}" color="$color{$newsock}" />|;
          print $newsock qq|<create user="user$number{$client}" x="$x{$client}" y="$y{$client}" color="$color{$client}" />|;
        }


     } else {
        my $buf = <$sock>;
        if ($buf) {
           print "Existing socket $number{$sock} is pending: " if ($verb > 3);
           chomp $buf;
           print "$buf\n" if ($verb > 3);
           ($x{$sock}) = $buf =~ /x="(.*?)"/;
           ($y{$sock}) = $buf =~ /y="(.*?)"/;
           
           foreach $client ($handles->handles) {
             print $client qq|<move user="user$number{$sock}" x="$x{$sock}" y="$y{$sock}" />|;
           }

        } else {
           print "Socket $number{$sock} is gone.\n" if ($verb > 2);
           $handles->remove($sock);
           foreach $client ($handles->handles) {
             print $client qq|<kill user="user$number{$sock}" />|;
           }
        }
     }
   }
}


