#!/usr/bin/perl

use strict;
use warnings;
use Data::Dumper;
use Mojo::IOLoop::Server;
use Mojo::IOLoop;
use File::Find qw( find );

my %allow_receive = ();
my %receiving = ();

# Listen on port 13000
Mojo::IOLoop->server({port => 13000} => sub {
  my ($loop, $stream) = @_;

  $stream->on(read => sub {
    my ($stream, $chunk) = @_;

    $chunk =~ s/\n//g;
    $chunk =~ s/\r//g;

    my $handle = $stream->handle;
    my $id = "$handle";

    if ($chunk =~ /^\$FILE_WRITE\$=(.*?)$/) {
      print STDERR $chunk."\n";
      $allow_receive{$id} = $1;
    }
    elsif ($chunk =~ /^\$QUIT\$$/) {
      print STDERR $chunk."\n";
      $stream->close();
    }
    elsif ($chunk =~ /^\$FILE_DELETE\$=(.*?)$/) {
      print STDERR $chunk."\n";
      my $file = $1;

      if (-e $file) {
        unlink $file;
      }

      $stream->write("§END§\n");
    }
    elsif ($chunk =~ /^\$FILE_READ\$=(.*?)$/) {
      print STDERR $chunk."\n";
      my $file = $1;

      if (open(F, "< $file")) {
        while (<F>) {
          $stream->write($_);
        }
        close(F);

        $stream->write("§END§\n");
      }
    }
    elsif ($chunk =~ /^\$DIR_READ\$=(.*?)$/) {
      print STDERR $chunk."\n";
      my $dir = $1;

      &find( sub {
        my $full_p = $File::Find::name;
        return unless -f $full_p;
        $full_p =~ s/^$dir//;
        $stream->write($full_p."\n");
      }, ( $dir ));

      $stream->write("§END§\n");
    }
    else {
      if ($chunk =~ /\$FILE_WRITE_END\$/) {
        $chunk =~ s/\$FILE_WRITE_END\$//;

        $receiving{$id} .= "$chunk";

        if (exists $receiving{$id} && $receiving{$id}) {
          if (open(F, "> $allow_receive{$id}")) {
            my @lines = split /§/, $receiving{$id};

            for (@lines) {
              print F $_."\n";
            }

            close(F);
          }
        }

        delete $allow_receive{$id};
        $receiving{$id} = "";

        $stream->write("§END§\n");
      }
      else {
        if (exists $allow_receive{$id}) {
          $receiving{$id} .= "$chunk";
        }
      }
    }
=pod
    elsif ($chunk =~ /^\$FILE_WRITE_END\$$/) {
      print STDERR $chunk."\n";

      if (exists $receiving{$id}) {
        if (open(F, "> $allow_receive{$id}")) {
          print F $receiving{$id};
          close(F);
        }
      }

      delete $allow_receive{$id};
      $receiving{$id} = "";

      $stream->write("§END§\n");
    }
    else {
      if (exists $allow_receive{$id}) {
        print STDERR "########## #$chunk#\n";
        $receiving{$id} .= "$chunk\n";
      }
    }
=cut

    # Got some data, time to write
    #$stream->write('HTTP/1.1 200 OK');
  });
});

# Start and stop loop
Mojo::IOLoop->start;

__END__

my $server = Mojo::IOLoop::Server->new( debug => 1 );

$server->on(accept => sub {
  my ($server, $handle) = @_;
  #  ...
});

$server->listen(port => 13000);
$server->start();
