| 1 | #!/usr/bin/perl -w |
|---|
| 2 | use strict; |
|---|
| 3 | |
|---|
| 4 | use FindBin; |
|---|
| 5 | use lib "$FindBin::RealBin/../lib"; |
|---|
| 6 | |
|---|
| 7 | use Getopt::Long; |
|---|
| 8 | use YAML; |
|---|
| 9 | use Plack::Runner; |
|---|
| 10 | use File::Pid; |
|---|
| 11 | use File::Spec::Functions qw{catfile}; |
|---|
| 12 | |
|---|
| 13 | GetOptions( |
|---|
| 14 | 'file=s' => \my $CONFIG_FILE, |
|---|
| 15 | ); |
|---|
| 16 | |
|---|
| 17 | $CONFIG_FILE ||= 'server.yml'; |
|---|
| 18 | -e $CONFIG_FILE or die "Config file $CONFIG_FILE not found\n"; |
|---|
| 19 | my $config = YAML::LoadFile($CONFIG_FILE); |
|---|
| 20 | my $command = shift or die "Usage: $0 <start|stop>\n"; |
|---|
| 21 | |
|---|
| 22 | my %run = ( |
|---|
| 23 | start => sub { |
|---|
| 24 | my $config = shift; |
|---|
| 25 | require BookmarksApp; |
|---|
| 26 | my $app = BookmarksApp->new({ config => $config })->to_app; |
|---|
| 27 | |
|---|
| 28 | my $server_root = $config->{server_root} || '.'; |
|---|
| 29 | my $listen = ':' . ($config->{port} || 5000); |
|---|
| 30 | my $access_log = catfile($server_root, 'access'); |
|---|
| 31 | my $error_log = catfile($server_root, 'errors'); |
|---|
| 32 | my $pid_file = catfile($server_root, 'pid'); |
|---|
| 33 | |
|---|
| 34 | my $runner = Plack::Runner->new(server => 'Starman'); |
|---|
| 35 | $runner->parse_options( |
|---|
| 36 | '--daemonize', |
|---|
| 37 | '--listen', $listen, |
|---|
| 38 | '--pid', $pid_file, |
|---|
| 39 | '--error-log', $error_log, |
|---|
| 40 | '--access-log', $access_log, |
|---|
| 41 | ); |
|---|
| 42 | $runner->run($app); |
|---|
| 43 | }, |
|---|
| 44 | |
|---|
| 45 | stop => sub { |
|---|
| 46 | my $config = shift; |
|---|
| 47 | my $server_root = $config->{server_root} || '.'; |
|---|
| 48 | |
|---|
| 49 | my $pid_file = File::Pid->new({ |
|---|
| 50 | file => catfile($server_root, 'pid'), |
|---|
| 51 | }); |
|---|
| 52 | |
|---|
| 53 | if (my $pid = $pid_file->running) { |
|---|
| 54 | kill 'TERM', $pid; |
|---|
| 55 | } |
|---|
| 56 | }, |
|---|
| 57 | ); |
|---|
| 58 | |
|---|
| 59 | exists $run{$command} or die "Unrecognized command $command\n"; |
|---|
| 60 | $run{$command}->($config); |
|---|