#!/usr/local/bin/perl

=head1 NAME

stop_server - script to stop an Ensembl server

=head1 SYNOPSIS

    ctrl_scripts/stop_server [-h] [-d N]

=head1 DESCRIPTION

This script starts an Ensembl server. Available options are:

    - delay after stopping server (not useful by itself, but when restarting
      server to allow heavy servers to shutdown properly)

Run 'ctrl_script/stop_server --help' for usage details.

=head1 LICENCE

This code is distributed under an Apache style licence:
Please see http://www.ensembl.org/code_licence.html for details

=head1 AUTHOR

Patrick Meidl <pm2@sanger.ac.uk>

=head1 CONTACT

Post questions to the EnsEMBL development list ensembl-dev@ebi.ac.uk

=cut


use strict;
use warnings;
no warnings 'uninitialized';

use FindBin qw($Bin);
use File::Basename qw( dirname );
use Sys::Hostname::Long;

my $serverroot;

BEGIN {
  $serverroot = dirname($Bin);
  unshift @INC, "$serverroot/conf";
};

use SiteDefs;

## Walk through the plugin tree and see if there's 'ctrl_scripts/*' in there
## any files starting with 00_stop* to 49_stop* will be executed before apache
## any files starting with 50_stop* to 99_stop* will be executed after
## same kind of thing happens with start_server
## all scripts must be perl scripts, as they are 'required'
my @stop_before;
my @stop_after;

my @T = reverse @{ $SiteDefs::ENSEMBL_PLUGINS || [] };
while( my( $dir, $name ) = splice(@T,0,2)  ) {
  $dir = "$dir/ctrl_scripts";
  if (opendir(DIR, $dir)) {
    my @files = readdir(DIR);
    push @stop_before, map {"$dir/$_"} grep {/^[0-5]?[0-9]_stop/} @files;
    push @stop_after, map {"$dir/$_"} grep {/^[5-9][0-9]_stop/} @files;
    closedir DIR;
  }
}

@stop_before = sort @stop_before;
@stop_after = sort @stop_after;

my $PID = $SiteDefs::ENSEMBL_PIDFILE;

use Getopt::Long;

my ($help, $delay);
&GetOptions(
    "delay=i"       => \$delay,
    "d=i"           => \$delay,
    "help"          => \$help,
    "h"             => \$help,
);
if ($help) {
    print qq(Usage:
    ctrl_scripts/stop_server
        [-d|--delay N]
        [-h|--help]
        
Options:
    -d N, --delay N : wait N seconds after stop \(to allow proper shutdown\)
    -h, --help      : print this help message
);
    exit;
}

my $hostname = hostname_long();

for (@stop_before) {
  eval { require $_; };
  warn $@ if $@;
}

eval {
  # stop the server
  warn "Stopping httpd daemon...\n";
  open (P, "<$PID") or warn
      "Could not open PID file $serverroot/logs/$hostname.httpd.pid: $!\n" .
      "STOP failed.\n";
      
  my $pid = <P>;
  close P;
  chomp $pid;
  
  if ($pid =~ /\d+/) {
  
    system("kill -TERM $pid") == 0 or warn
        "Could not stop server: $!.\n" .
        "STOP failed.\n";
  
    if ($delay) {
        warn "Waiting $delay seconds for server to shut down...\n";
        sleep $delay;
    }
  
  } else {
    warn "Invalid PID: $pid\nSTOP failed.\n";
  }
};

warn $@ if $@;

for (@stop_after) {
  eval { require $_; };
  warn $@ if $@;
}


warn "Done.\n";

