#!/usr/bin/env perl

use strict;
use warnings FATAL => qw( all );

use lib "./lib";

use Nebulous::Client;
use IO::Select;
use IO::Socket;

my $neb = Nebulous::Client->new(
#    proxy   => 'http://localhost:80/nebulous'
    proxy   => 'http://alala:80/nebulous'
);

my $key = shift || 'foobar';
my $kids = shift || 1;

my $s = IO::Select->new();

foreach my $id ( 1..$kids ) {
    my ($sock_parent, $sock_child) = IO::Socket->socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC);
    $s->add($sock_parent);

    my $pid = fork;

    unless ( $pid )  {
        child($sock_child, $id);
        exit 0;
    }
    # parent
}

while ($kids) {
    foreach my $child ($s->can_read(1)) {
        my $string = <$child>;
        my @events = split(/\n/, $string) if $string;
        print join("\n", @events), "\n" if scalar @events;
    }
}

#while ( $kids ) {
#    wait();
#    $kids --;
#}

our $my_sock;

sub child
{
    my ($sock_child, $id) = @_;

    $my_sock = $sock_child;

    # child
    my $fname = "${key}_$id";
    print $sock_child "$$ : i'm a little tea pot using key: $fname\n";
    my $fh = $neb->open_create( $fname );
    child_die("can't create file $fname") unless $fh;

    print $fh "fooby\n";

    close $fh;

    $fh = $neb->open( $fname, 'read' ) or child_die("can't open file");
    close $fh;

    $neb->lock( $fname, 'read' );
    $neb->unlock( $fname, 'read' );
    $neb->replicate( $fname );
    $neb->cull( $fname );

    print $sock_child "$$ : half way\n";

    $neb->find( $fname );
    $neb->copy( $fname, $fname . "_copy" );
    $neb->move( $fname, $fname . "_move" );
    $neb->delete( $fname . "_copy" );
    $neb->delete( $fname . "_move" );

    print $sock_child "$$ : all done!\n";

    $sock_child->flush;
    sleep 10;

    return 1;
}

sub child_die
{
    print $my_sock $@;
    shutdown($my_sock, 2);
    exit 1;
}
