#!/usr/local/bin/perl

# super simple tcp server that just prints out what 
# it's given on a particular port.
#
# run this in one window (perl ./simple_agid.pl -D)
# telnet localhost 4573 in another window.

use strict;
use IO::Socket::INET;
use IO::Select;
use Getopt::Std;

my %opt;
getopts('D', \%opt);
# Debug

my $sock = IO::Socket::INET->new( Listen => 5,
                                  LocalAddr => 'localhost',
                                  LocalPort => '4573',
                                  Proto => 'tcp',
                                  Reuse => 1,
                                );

die "cant set up server: $!\n" unless $sock;

my $sel = new IO::Select( $sock );
while(my @ready = $sel->can_read) {
    for my $fh (@ready) {
        if($fh == $sock) {
            # Create a new socket
            my $new = $sock->accept;
            my $peer = $new->peerhost;
            $sel->add($new);
            debug( "${peer}: managing new socket." );
        } else {
            # Process socket
            while(my $line = <$fh>){
                chomp $line;
                chop $line if( $line =~ /\r$/ );

                my $peer = $fh->peerhost;
                debug( "${peer}:  [$line]" );
                if( $line =~ /^quit$/i ){
                    last;
                }
            }

            $sel->remove($fh);
            $fh->close;
        }
    }
}

sub debug {
    my $msg = join('', @_);
    warn "$msg\n" if $opt{D};
}
