package Barkani::Faxdispatch;

use YAML::XS;
use Data::Dumper;
use LWP::UserAgent;
use HTTP::Request;
use URI;

my @header_line;

my $CONFIGURATION = YAML::XS::LoadFile("/usr/local/etc/fax-dispatch.yaml");
die "No configuratoin at '/usr/local/etc/fax-dispatch.yaml': $!"
  unless $CONFIGURATION;

sub pass_message {
  my $email_account = shift;

  {
    while (1) {
      my $header_line = <STDIN>;
      chomp($header_line);
      push @header_line,$header_line;
      last
	unless length $header_line;
    }
  }

  (my $number_line) = grep /^X-J2-Phone-Number/, @header_line;
  if ((my $number) = $number_line =~ m/^X-J2-Phone-Number: (\d+)$/) {
    warn "Fax was sent to $number";
    if (my $destination = $CONFIGURATION->{$email_account}->{$number} ) {
      my $uri = URI->new();
      $uri->scheme('http');
      $uri->host($destination->{host});
      $uri->port($destination->{port});
      $uri->path($destination->{path});
      my $content = join("\r\n", @header_line,slurp_stdin());
      warn "Sending ", length($content), " octets to $uri";
      my $response = LWP::UserAgent->new->post($uri,Content => $content);
      warn $response->status_line;
      warn $response->decoded_content();
    }
  } else {
    warn "Could not find a telphone number anywhere in @header_line";
  }
}

sub slurp_stdin {
  my @stdin;
  while (my $line = <STDIN> ) {
    chomp($line);
    push @stdin,$line;
  }
  warn "Done with stdin: ", scalar @stdin, " lines";
  return @stdin;
}

package main;

sub run {
  my $email_account = $ARGV[0];
  close STDERR;
  open STDERR,">>/tmp/fax-dispatch.log";
  warn "Launch at ",scalar(localtime);
  Barkani::Faxdispatch::pass_message($email_account);
}

1;
