#!/usr/local/bin/perl

use strict;
use v5.8.1;

use warnings;
use Data::Dumper;
use Getopt::Long;
use UNIVERSAL::require;

my $options;
my $foreground;
my $command = shift || '';

BEGIN {

	my %opt = ();
	GetOptions (\%opt, qw/
		port=i 
		session_alias|session|alias=s
		lib|I=s
		version
		foreground
		debug
		/);
	# $opt{foreground} # Run in the foreground
	unshift(@INC, map {s/~/$ENV{HOME}/;$_} split(/:/=>$opt{lib})) if (exists $opt{lib});
	$options = \%opt;
}


my %options = %{$options};

$options{session_alias} ||= 'POEIKCd';
$options{port} ||= 54321;
$foreground = exists $options{foreground} || exists $options{debug} ;

use POEIKCdaemon;
use POEIKCdaemon::Utility;

if (exists $options{debug}) {
	no warnings;
	$POEIKCdaemon::DEBUG = $options{debug};
	for (qw/POEIKCdaemon POEIKCdaemon::Utility/) {
		Class::Inspector->loaded( $_ ) or die;
	}
}

our $VERSION = $POEIKCdaemon::VERSION;

for ($command) {

	exists $options{version} and do {
		printf "poeikcd version: %s\n", $VERSION;
		last;
	};

	/stop/i and do {
		if( Proc::ProcessTable->use ){
			my $proc;
			for my $ps( @{Proc::ProcessTable->new->table} ) {
				if ($ps->{pid} != $$ and $ps->{fname} eq 'poeikcd'){
					$proc++;
				}
			}
			$proc or last;
		}
		use POE::Component::IKC::ClientLite;
		my ($name) = $0 =~ /(\w+)\.\w+/;
		$name .= $$;
		my $ikc = create_ikc_client(
			ip => '127.0.0.1',
			port => $options{port},
			name => $name,
		);
		$ikc or do{
			if( Proc::ProcessTable->use ){
				for my $ps( @{Proc::ProcessTable->new->table} ) {
					if ($ps->{pid} != $$ and $ps->{fname} eq 'poeikcd'){
						print $ps->{cmndline},"\n\n";
					}
				}
			}
			printf "%s\n\n",$POE::Component::IKC::ClientLite::error; 
			exit;
		};
		my $ret = $ikc->post_respond(
			$options{session_alias}.'/method_respond' => 
			['POEIKCdaemon::Utility' => 'stop']
		);
		$ikc->error and die($ikc->error);
		my ($t1, $t2, $pid, $port) = @{$ret};
		printf "poeikcd is stopped. (PID:%s, Port:%s, %s)\n", 
			$pid, $port, $t1  unless $foreground;
		last;
	};
	/start/i and do {
		use Proc::Daemon;
		printf "poeikcd is Started. (%s)\n",scalar(localtime) unless $foreground;
		Proc::Daemon::Init unless $foreground;
		POEIKCdaemon->daemon(%options);
		last;
	};

	print(<<'	HELP_text');
	Usage: poeikcd {start|stop}
	
	Option
	-Idirectory --lib    specify @INC/#include directory
	-v                   poeikcd version

	HELP_text
}


__END__

=head1 NAME

poeikcd - POE IKC daemon

=head1 SYNOPSIS

  poeikcd start -p=54321 # or   poeikcd start --port=54321
  poeikcd stop  -p=54321 # or   poeikcd stop  --port=54321

=head1 DESCRIPTION

poeikcd (L<POEIKCdaemon>) is daemon of POE::Component::IKC

=head1 AUTHOR

Yuji Suzuki E<lt>yuji.suzuki.perl@gmail.comE<gt>

=head1 LICENSE

This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself.

=head1 SEE ALSO

L<POEIKCdaemon>
L<POE::Component::IKC::ClientLite>

=cut
