#!/usr/bin/env perl

use strict;
use warnings;

use Hermes;
use Janus::Path;
use Janus::Conf;
use Janus::Ctrl;
use Vulcan::OptConf;
use Vulcan::ProcLock;
use Vulcan::Sudo;

Vulcan::Sudo->sudo();

$| ++;

$Vulcan::OptConf::THIS = 'janus';

my $option = Vulcan::OptConf->load();
my %o = $option->get( qw( show-path ) )->dump();

my $conf = Janus::Conf->new( $o{conf} );
my $path = Janus::Path->new( $o{path} );
die "janus not set up.\n" unless $path->check();

=head1 SYNOPSIS

Show janus status. If no names are given, show all known janus events.

$0 [names ..] [--show-conf]

=cut
my $range = Hermes->new( $option->dump( 'range' ) );
my @name = @ARGV
    ? grep { $conf->dump( $_ ) } map { $range->load( $_ )->list() } @ARGV
    : $conf->names();

my %stat;

for my $name ( @name )
{  
    my $ctrl = $path->path( run => "$name.ctrl" );

    next unless -f $ctrl || -l $ctrl;
    $ctrl = Janus::Ctrl->new( $name => $ctrl );

    my $lock = $path->path( run => "$name.lock" );
    my $pid = Vulcan::ProcLock->check( $lock );
    my %ctrl; 

    $ctrl{pid} = int $pid if $pid;
    $ctrl{excluded} = $range->dump() if $range->load( $ctrl->excluded() )->list;

    map { $ctrl{ $_->[1] }{ $_->[2] } = $_->[3] } $ctrl->stuck();
    $stat{$name} = \%ctrl if %ctrl;
}

YAML::XS::DumpFile STDOUT $path->path() if $o{'show-path'};
YAML::XS::DumpFile STDOUT \%stat if %stat;
exit 0;