#!/usr/bin/env perl
use strict; use warnings;
use lib '/home/nuclon/workspace/qless-perl/lib';
use Daemon::Generic;
use File::Basename;
use Class::Load qw(load_class);
use Getopt::Long;
use Qless;
use Qless::Worker;

newdaemon(
	progname => basename($0),
);


sub gd_preconfig {}

sub gd_run {
	my $self = shift;

	my $opt = $self->{'qless_opt'};
	unshift @INC, @{ $opt->{'include'} } if $opt->{'include'};
	my $worker = Qless::Worker->new(%{ $opt });

	# Preload modules
	if ($opt->{'import'}) {
		foreach my $class (@{ $opt->{'import'} }) {
			load_class $class;
		}
	}

	$worker->run;
}

sub gd_getopt {
	my $self = shift;

	my $opt = {};
	GetOptions($opt,
		'pid=s',
		'host=s',
		'socket=s',
		'queue|q=s@',
		'include|I=s@',
		'interval|i=i',
		'workers|w=i',
		'name|n=s',
		'import|m=s@',
		'resume|r',
		'debug',
		'help|h',
	) or exit($self->gd_usage);


    if (@ARGV < ($self->{gd_args}{minimum_args} || 1)) {
        exit($self->gd_usage());
    }
    if (@ARGV > ($self->{gd_args}{maximum_args} || 1)) {
        exit($self->gd_usage());
    }

	my $do = $ARGV[0];
	$opt->{'debug'} = $self->{'debug'} = 1 if $do eq 'debug';

	if ($do =~ /^(?:(?:re)?start|debug)$/ && !$opt->{'queue'}) {
		print "ERROR: Queues are not specified\n\n";
		exit(gd_usage());
	}
	$opt->{'queue'} = [ split(/,/, join(',', @{ $opt->{'queue'} })) ] if $opt->{'queue'};
	$self->{'gd_pidfile'} = $opt->{'pid'};
	$self->{'qless_opt'} = $opt;
}

sub gd_pidfile {
	my $self = shift;
	$self->{gd_pidfile} = "$self->{gd_pidbase}.pid";
}

sub gd_usage {
	my $self = shift;
	print <<EOB;
usage: $0 [options] { start | stop | restart | status | help | version | debug }
options:
  --host server:port
  --socket unix_socket_path
     The host:port or unix_socket to connect to as the Redis server

  -q queue_name
  --queue queue_name
     The queues to pull work from

  -I path
  --include path
      Path(s) to include when loading jobs

  -w count
  --workers count
      How many processes to run.

  -i seconds
  --interval seconds
      The polling interval

  -n worker_name
  --name worker_name
      Name to identify your worker as

  -r
  --resume
      Try to resume jobs when the worker agent is restarted

  -m module_name
  --import
      The modules to preemptively import

  --pid
      PID file to use

commands:
  start           Starts a new $0 if there isn't one
                  running already
  stop            Stops a running $0
  restart         Stops a running $0 if one is running.
                  Starts a new one.
  status          Show daemon state.
  help            Display this usage info
  version         Display the version of $0
  debug           Starts a new $0 in the foreground
EOB

	1;
}

sub gd_version {
	my $self = shift;
	print $Qless::VERSION;
	exit(1);
}
