#!/usr/local/bin/perl

=head1 NAME

start_server - script to start an Ensembl server

=head1 SYNOPSIS

    ctrl_scripts/start_server [-rXh]

=head1 DESCRIPTION

This script starts up an Ensembl server. Available options are:

    - delete conf/config.packed before start
    - start Apache in single server mode

Run 'ctrl_script/start_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;
use Getopt::Long;

my ($help, $rmconfig, $single, $flush);
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_start* to 49_start* will be executed before apache
## any files starting with 50_start* to 99_start* will be executed after
## same thing happens with stop_server
## all scripts must be perl scripts, as they are 'required'

use Data::Dumper;

my @start_before;
my @start_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 @start_before, map {"$dir/$_"} grep {/^[0-5]?[0-9]_start/} @files;
    push @start_after, map {"$dir/$_"} grep {/^[5-9][0-9]_start/} @files;
    closedir DIR;
  }
}

@start_before = sort @start_before;
@start_after = sort @start_after;

my $confdir = 'conf';
&GetOptions(
  "confdir=s"       => \$confdir,
  "rmconfig"      => \$rmconfig,
  "r"             => \$rmconfig,
  "flush"         => \$flush,
  "f"             => \$flush,
  "X"             => \$single,
  "single"        => \$single,
  "help"          => \$help,
  "h"             => \$help,
);

warn "
==============================================================================
 Starting server with configurations from $confdir
";

if ($help) {
  print qq(
	Usage:
    ctrl_scripts/start_server
      [-r|--rmconfig]
      [-f|--flush]
      [-X|--single]
      [-h|--help]
        
Options:
  -r, --rmconfig  : remove conf/config.packed before restarting the server and flush memcached
	-f, --flush     : flush memcached storage!
  -X, --single    : start Apache in single server mode
  -h, --help      : print this help message
);
    exit;
}

my $hostname = hostname_long();

# start the server
if ($rmconfig) {
  warn " Removing config.packed...\n";
  my $ok = unlink "$serverroot/$confdir/config.packed";
  if ($ok) {
    warn " Removed config.packed....\n";
  } else {
    warn " Could not delete $serverroot/$confdir/config.packed: $!\n[WARN] Starting with old config.packed!\n";
  }
}

## Check memcached servers version
  warn " Checking memcached compatibility...\n";
  my $res = system("$serverroot/ctrl_scripts/memcached version");
  if ($res >> 8 > 0) {
    die " failed\nPlease check www.ensembl.org/info/docs/webcode/memcached\n";
  }


if( $flush || $rmconfig ) {
  # Flush memcached
  my $cmd = "$serverroot/ctrl_scripts/memcached flush_all";
  my @res = `$cmd`; chomp @res;
  warn " Flushed memcached entries for this server (@res)\n";
}
warn "==============================================================================\n";

# LOAD LSF ENVIRONMENT - REQUIRED FOR BLAST
my $cmd = ". /usr/local/lsf/conf/profile.lsf;" if -e '/usr/local/lsf/conf/profile.lsf';

my $exe =  defined ($SiteDefs::APACHE_BIN) ? $SiteDefs::APACHE_BIN : ($SiteDefs::APACHE_DIR."/bin/httpd");
$cmd .= "$exe -d $SiteDefs::APACHE_DIR -f $serverroot/$confdir/httpd.conf" . ($single ? " -X &" : "");

require $_ for @start_before;
system($cmd) == 0 or die " Could not start server: $!.\n[FATAL] Server start failed.\n";
require $_ for @start_after;
