#!/usr/bin/env perl

use Mojolicious::Lite;
use Mojo::URL;
use Path::Tiny qw( path );
use Getopt::Long qw( GetOptions );
use Mojo::JSON qw( encode_json decode_json );

my $daemon = 0;
my $kill   = 0;
my $host   = 'localhost';

GetOptions(
  "d"      => \$daemon,
  "k"      => \$kill,
  "host=s" => \$host,
);

my $bindir    = path(__FILE__)->parent->absolute;
my $distdir   = $bindir->parent->parent;

my $config_file = $bindir->child('httpd.json');

if(-r $config_file)
{
  my $config = decode_json($config_file->slurp);
  my $pid = $config->{pid};
  if(defined $pid)
  {
    kill 'KILL', $pid;
  }
}

exit if $kill;

if($daemon)
{
  require Proc::Daemon;
  my $daemon = Proc::Daemon->new(
    child_STDOUT => $bindir->child('httpd.log')->stringify,
    child_STDERR => $bindir->child('httpd.log')->stringify,
  );
  $daemon->Init;
}

my $url = Mojo::URL->new('http://localhost/corpus/dist/');
$url->host($host);
$url->port(do {
  require IO::Socket::INET;
  IO::Socket::INET->new(Listen => 5, LocalAddr => "127.0.0.1")->sockport;
});

my %config = (
  root => $distdir->child('corpus/dist')->stringify,
  pid  => $$,
  url => $url->to_string,
);
$config_file->spew(encode_json(\%config));

plugin( 'Directory', root => $distdir->stringify );

get '/corpus/dist/about.json' => sub {
  shift->render(
    json => {
      ident   => 'AB Test HTTPd',
    }
  );
};

$url->path('/');
@ARGV = ('daemon', -l => "$url");
app->start;
