#!/usr/bin/perl -w

#  You may distribute under the terms of the GNU General Public License
#
#  (C) Paul Evans, 2008-2010 -- leonerd@leonerd.org.uk

use strict;
use warnings;

use Circle;
use IO::Async::Loop 0.37;
use IO::Async::Stream;

use Getopt::Long;
use Socket qw( AF_INET SOCK_STREAM );

my $PORT;
my $SOCKPATH;

GetOptions(
   'p|port=i'   => \$PORT,
   's|socket=s' => \$SOCKPATH,
) or exit(1);

defined $PORT and defined $SOCKPATH and die "Cannot specify both --port and --socket\n";

my $loop = IO::Async::Loop->new();

my $circle = Circle->new( loop => $loop );

if( defined $PORT ) {
   $circle->listen(
      addr => {
         family   => 'inet',
         socktype => 'stream',
         port     => $PORT,
      },
      on_fail => sub { print STDERR "Cannot $_[0] - $_[-1]\n"; },
      on_listen_error  => sub { print STDERR "Cannot listen\n"; },
   );
}
elsif( defined $SOCKPATH ) {
   if( -e $SOCKPATH ) {
      unlink $SOCKPATH or die "Cannot unlink $SOCKPATH - $!";
   }
   $circle->listen(
      addr => {
         family   => 'unix',
         socktype => 'stream',
         path     => $SOCKPATH,
      },
      on_fail => sub { print STDERR "Cannot $_[0] - $_[-1]\n"; },
      on_listen_error => sub { print STDERR "Cannot listen\n"; },
   );
}
else {
   $circle->on_stream( IO::Async::Stream->new_for_stdio );
}

$SIG{__WARN__} = sub {
   local $SIG{__WARN__}; # disable during itself to avoid looping
   $circle->warn( @_ );
};

$loop->loop_forever;
