#!/usr/bin/perl

eval 'exec /usr/bin/perl  -S $0 ${1+"$@"}'
    if 0; # not running under some shell

use strict;
use warnings;

use Getopt::Long;
use Pod::Usage;
use Server::Starter qw(start_server restart_server);

my %opts = (
    port => [],
);

GetOptions(
    map {
        $_ => do {
            my $name = (split '=', $_, 2)[0];
            $name =~ s/-/_/g;
            $opts{$name} ||= undef;
            ref($opts{$name}) ? $opts{$name} : \$opts{$name};
        },
    } qw(port=s interval=i log-file=s pid-file=s signal-on-hup=s status-file=s
         restart help version),
) or exit 1;
pod2usage(
    -exitval => 0,
    -verbose => 1,
) if $opts{help};
if ($opts{version}) {
    print "$Server::Starter::VERSION\n";
    exit 0;
}

if ($opts{restart}) {
    restart_server(%opts);
    exit 0;
}

# validate options
die "server program not specified\n"
    unless @ARGV;

start_server(
    %opts,
    exec => \@ARGV,
);

__END__

=head1 NAME

start_server - a superdaemon for hot-deploying server programs

=head1 SYNOPSIS

  start_server [options] -- server-prog server-arg1 server-arg2 ...

  # start Plack using Starlet listening at TCP port 8000
  start_server --port=8000 -- plackup -s Starlet --max-workers=100 index.psgi

=head1 DESCRIPTION

This script is a frontend of L<Server::Starter>.  For more information please refer to the documenation of the module.

=head1 OPTIONS

=head2 --port=(port|host:port)

TCP port to listen to (if omitted, will not bind to any ports)

=head2 --interval=seconds

minimum interval to respawn the server program (default: 1)

=head2 --signal-on-hup=SIGNAL

name of the signal to be sent to the server process when start_server receives a SIGHUP (default: SIGTERM)

=head2 --pid-file=filename

if set, writes the process id of the start_server process to the file

=head2 --status-file=filename

if set, writes the status of the server process(es) to the file

=head2 --restart

this is a wrapper command that reads the pid of the start_server process from --pid-file, sends SIGHUP to the process and waits until the server(s) of the older generation(s) die by monitoring the contents of the --status-file

=head2 --help

prints this help

=head2 --version

prints the version number

=head1 AUTHOR

Kazuho Oku E<lt>kazuhooku@gmail.comE<gt>
Copyright (C) 2009 Cybozu Labs, Inc.

=head1 SEE ALSO

L<Server::Starter>

=head1 LICENSE

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

=cut
