#!/usr/bin/perl -T -w -I/opt/eprints3/perl_lib 

######################################################################
#
# chkconfig: - 85 15
# description: Start the eprints indexer daemon as the correct user
#
######################################################################
#
#
# Copyright 2000-2008 University of Southampton. All Rights Reserved.
# 
#  This file is part of GNU EPrints 3.
#  
#  Copyright (c) 2000-2008 University of Southampton, UK. SO17 1BJ.
#  
#  EPrints 3 is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.
#  
#  EPrints 3 is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#  
#  You should have received a copy of the GNU General Public License
#  along with EPrints 3; if not, write to the Free Software
#  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
######################################################################

use EPrints::SystemSettings;
use English;
use POSIX;

use strict;

if( $REAL_USER_ID != 0 )
{
	print "This script is intended to start the eprints indexer as a service.\nIt should only be run as root.\nExiting.\n";
	exit 1;
}
if( !defined $ARGV[0] || $ARGV[0] !~ m/^(start|stop|status)$/ )
{
	print "Usage: $0 {start|stop|status}\n";
	exit 1;
}
my $opt = $1;

# These are not going via Platform, but this is a UNIX script, so meh.
my $user = $EPrints::SystemSettings::conf->{'user'};
my $group = $EPrints::SystemSettings::conf->{'group'};
my $uid = (getpwnam($user))[2];
my $gid = (getgrnam($group))[2];
my @sgroups = ($gid); # gid + supplementary groups
while(my( undef, undef, $gid, $members ) = getgrent())
{
	push @sgroups, $gid if $members =~ /\b$user\b/;
}

$REAL_GROUP_ID = $EFFECTIVE_GROUP_ID = "@sgroups";
$REAL_USER_ID = $EFFECTIVE_USER_ID = $uid;

my $indexer_cmd = $EPrints::SystemSettings::conf->{'base_path'}.'/bin/indexer';
$| = 0;
if( $opt eq 'start' )
{
	print 'Starting EPrints Indexer: ';
}
if( $opt eq 'stop' )
{
	print 'Stopping EPrints Indexer: ';
}
delete $ENV{'PATH'};
my $rv = system( $indexer_cmd, $opt );
$rv = $rv >> 8;
if( $opt eq 'start' || $opt eq 'stop' ) 
{
	if( $rv == 0 )
	{
		print '                                 [  OK  ]'."\n";
	}
	else
	{
		print '                                 [FAILED]'."\n";
	}
}

exit $rv;
