#!/usr/bin/env perl
use strict;
use warnings;
use FindBin;
use File::Spec;
use lib "$FindBin::Bin/../lib";


if (scalar(@ARGV)) {
  if (my $action = (grep { $_ eq $ARGV[0] } qw( backend daemon frontend help upgrade version ))[0]) {
    $ENV{MOJO_MODE} ||= 'production';
    exec File::Spec->catfile($FindBin::Bin, 'convos-backend')  => do { shift @ARGV; @ARGV } if $action eq 'backend';
    exec File::Spec->catfile($FindBin::Bin, 'convos-frontend') => do { shift @ARGV; @ARGV } if $action eq 'frontend';
  }

  $ENV{CONVOS_BACKEND_EMBEDDED} //= 1 if $ARGV[0] eq 'daemon';
  $ENV{CONVOS_BACKEND_ONLY} = $ENV{CONVOS_REDIS_URL} = 'invalid://' if $ARGV[0] eq 'help';
}
test_mode() if $ENV{CONVOS_REDIS_URL} and $ENV{CONVOS_REDIS_URL} =~ s,^test\b(?![.-])(\://)?,,;

require Mojolicious::Commands;
require Convos;
my $commands = Mojolicious::Commands->new(app => Convos->new);
unshift @{$commands->namespaces}, 'Convos::Command';
$commands->run(@ARGV);

#=============================================================================

sub test_mode {
  $ENV{CONVOS_DEBUG} //= 1;
  $ENV{CONVOS_REDIS_URL} ||= 'localhost/13';
  $ENV{MOJO_IRC_DEBUG} //= 1;
  $ENV{MOJO_LOG_LEVEL} ||= 'debug';
  $ENV{MOJO_REDIS_DEBUG}        //= 1;
  $ENV{MOJO_ASSETPACK_NO_CACHE} //= 1;
}

sub usage {
  !print <<"USAGE";

# Single process
$0 daemon --listen http://*:8080

# Separate backend and single process frontend
$0 backend start
$0 daemon --listen http://*:8080

# Separate backend and preforked frontend
$0 backend start
$0 prefork --listen http://*:8080

# Print relevant version information
$0 version

# More help
$0 help
$0 help backend
$0 help daemon
$0 help prefork

https://github.com/Nordaaker/convos#readme

USAGE
}
