#! /bin/bash
# ----------------------------------------------------------------------
# File: eos
# Author: Andreas-Joachim Peters - CERN
# ----------------------------------------------------------------------

# ************************************************************************
# * EOS - the CERN Disk Storage System                                   *
# * Copyright (C) 2011 CERN/Switzerland                                  *
# *                                                                      *
# * This program 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 3 of the License, or    *
# * (at your option) any later version.                                  *
# *                                                                      *
# * This program 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 this program.  If not, see <http://www.gnu.org/licenses/>.*
# ************************************************************************
#
#****************************************************************************
#                      eos.init
#
# chkconfig: 345 95 5
# description: EOS Xrootd Initialisation Script
#****************************************************************************

# Source function library
. /etc/rc.d/init.d/functions

# Variables
prog="xrootd"
sysconfigfile="eos"

# Defaults
XRD_LOCATION="/usr/"
EOS_LOCATION="/usr/"
XRD_MAXFD=65000
XRD_USER="daemon"
XRD_LOGDIR="/var/log/eos"
XRD_COREDIR="/var/spool/eos/"
XRD_ADMINDIR="/var/spool/eos/admin"
XRD_CONFIGDIR="/var/eos/"
XRD_AUTHDIR="/var/eos/auth/"
XRD_STAGEDIR="/var/eos/stage/"
XRD_CONFIG="/etc/xrd.cf"
XRD_ROLEFLAG=""

FRETVAL=0
RETVAL=0

USER=`whoami`
# Source sysconfig files
if [ -f /etc/sysconfig/$sysconfigfile ]; then
        . /etc/sysconfig/$sysconfigfile
fi


cleanup() {
        if [ "${XRD_ROLES}" = "fst" ]; then
	    echo ""
	fi
}

# fix the /etc/eos.keytab ownership to XRD_USER

if [ -e /etc/eos.keytab ]; then
	chown $XRD_USER /etc/eos.keytab
	chmod 400 /etc/eos.keytab
fi

#
EOS_CONFIGDIR=${EOS_CONFIGDIR-`cat /etc/xrd.cf.mgm | grep -v "^#" | grep mgmofs.configdir | awk '{print \$2}' 2>/dev/null`/`hostname -f`};

start() {
	# Start xrootd daemons
	echo
	for i in ${XRD_ROLES}; do
            XRD_ROLEFLAG="";
            if [ "$i" = "mgm" ]; then
		    XRD_ROLEFLAG="-m "
 	    fi
	    
	        # Load the appropriate sysconfig file for the role
	        if [ -f /etc/sysconfig/$sysconfigfile.$i ]; then
                        . /etc/sysconfig/$sysconfigfile.$i
                else
		        # Load default
		        if [ -f /etc/sysconfig/$sysconfigfile ]; then
                                . /etc/sysconfig/$sysconfigfile
                        fi
                fi

		# Check to see if a dedicated config file exists
		_XRD_CONFIG=${XRD_CONFIG}
		if [ -f ${XRD_CONFIG}.$i ]; then
		        _XRD_CONFIG=${XRD_CONFIG}.$i
		fi
                echo -n $"Starting $prog as $i "

		# Check to see whether the xrootd daemon for this role is 
                # already running
		pid=`pidofproc $prog.$i`
		if [ -n "$pid" ]; then
                        echo -n $"- already started"
			failure
			echo
                else
		        # Setup the base xrootd options
		        _XRD_OPTIONS="-n $i -c ${_XRD_CONFIG} ${XRD_ROLEFLAG} -l ${XRD_LOGDIR}/xrdlog.$i -b -R${XRD_USER}"
			_XRD_OPTIONS=${_XRD_OPTIONS%' '}
			echo  with ${_XRD_OPTIONS}
			# Setup xrootd environment

                        if [ -z "${XRD_USER}" ]; then 
			    mkdir -p ${XRD_COREDIR}/core/$i ${XRD_ADMINDIR} ${XRD_LOGDIR} ${XRD_CONFIGDIR} ${EOS_CONFIGDIR}/
			    touch ${EOS_CONFIGDIR}/default.eoscf
			    chown -R ${XRD_USER} ${XRD_COREDIR}; 
			    chmod -R 775 ${XRD_COREDIR}
			else
			    mkdir -p ${XRD_COREDIR}/core/$i ${XRD_ADMINDIR} ${XRD_LOGDIR} ${XRD_CONFIGDIR} ${EOS_CONFIGDIR}/
			    touch ${EOS_CONFIGDIR}/default.eoscf
			    chown -R ${XRD_USER} ${XRD_ADMINDIR} ${XRD_LOGDIR} ${XRD_CONFIGDIR}
			    chown -R ${XRD_USER} ${XRD_COREDIR}; 
			    chmod -R 775 ${XRD_COREDIR}
			fi

	                # dir to store credentials			
			mkdir -p ${XRD_AUTHDIR}/
			chown ${XRD_USER} ${XRD_AUTHDIR}
			setfacl -m default:u:${XRD_USER}:r ${XRD_AUTHDIR}
 
                        # dir to store intermediate stage files (only FST gateways)
			mkdir -p ${XRD_STAGEDIR}/
			chown ${XRD_USER} ${XRD_STAGEDIR}

			cd ${XRD_COREDIR}/core/$i

			if [ ${XRD_USER} = "$USER" ]; then
			    ulimit -c ${DAEMON_COREFILE_LIMIT-unlimited}
			    [ -f /etc/sysconfig/$sysconfigfile ] && source /etc/sysconfig/$sysconfigfile ;cd ${XRD_COREDIR}/core/; env LD_LIBRARY_PATH=${EOS_LOCATION}/lib:${LD_LIBRARY_PATH} ${XRD_LOCATION}/bin/$prog ${_XRD_OPTIONS}
			else
			    ulimit -n ${XRD_MAXFD}
			    ulimit -c ${DAEMON_COREFILE_LIMIT-unlimited}
			    [ -f /etc/sysconfig/$sysconfigfile ] && source /etc/sysconfig/$sysconfigfile ;cd ${XRD_COREDIR}/core/; env LD_LIBRARY_PATH=${EOS_LOCATION}/lib:${LD_LIBRARY_PATH} ${XRD_LOCATION}/bin/$prog ${_XRD_OPTIONS}
			fi

			# Write the pid to a file
			RETVAL=$?
			if [ $RETVAL -eq 0 ]; then
			        pid=`ps -eo pid,ppid,comm,cmd | grep -v egrep | egrep "$prog -n $i -c /etc/xrd" | awk '{print $1}'`
				if [ $USER = "root" ]; then
				    rm -f /var/run/$prog.$i.pid
				fi
				if [ -n "$pid" ]; then
                                        echo $pid > /var/run/$prog.$i.pid
					if [ $USER = "root" ]; then
					    chown ${XRD_USER} /var/run/$prog.$i.pid
					fi
					    
                                        RETVAL=0
				else
                                        RETVAL=1
				fi      
			fi

                        [ $RETVAL -eq 0 ] && success $"$base startup" || failure $"$base startup"
                        echo
                        if [ $RETVAL -eq 0 ]; then
			    if [ $USER = "root" ]; then			    
                                touch /var/lock/subsys/$prog.$i
				chown ${XRD_USER} /var/lock/subsys/$prog.$i
			    fi
                        else
                                FRETVAL=$RETVAL
                        fi
		fi
        if [ "$i" = "fed" ]; then
           /etc/rc.d/init.d/cmsd start
        fi
	done
 
        RETVAL=$FRETVAL
        return $RETVAL
}

stop() {
	GRETVAL=0
	if [ -n "$1" ]; then
		XRD_ROLES="$1";
	fi	
	for role in $XRD_ROLES; do 
		if [ "$XRD_ROLES" = "mgm" ]; then
   			XRD_ROLEFLAG="-m "
		fi
		RETVAL=0
	        if [ "$role" = "fed" ]; then
	        	/etc/rc.d/init.d/cmsd stop
			GRETVAL=$?
	        fi 
		RETVAL=1
		echo -n $"Stopping $prog: $role"
	  	      	# try killing by grep
		for pid in `ps -eo pid,ppid,comm,cmd | grep -v egrep | egrep "$prog -n $role -c /etc/xrd" | awk '{print $1}'`; do
	        	if [ -n "$pid" ]; then
				kill -15 $pid;
				usleep 200000
				[ -d "/proc/$pid" ] && sleep 1 
				[ -d "/proc/$pid" ] && sleep 1 
				[ -d "/proc/$pid" ] && sleep 1 
				[ -d "/proc/$pid" ] && sleep 1 
				[ -d "/proc/$pid" ] && sleep 1 
				[ -d "/proc/$pid" ] && sleep 1 && kill -9 $pid 2>/dev/null && usleep 200000
				[ -d "/proc/$pid" ] || RETVAL=0
				[ "$RETVAL" != "0" ] && GRETVAL=$RETVAL
				[ $USER = "root" ] && [ "$RETVAL" = "0" ] && [ -f /var/lock/subsys/$prog.$role ] && rm -f /var/lock/subsys/$prog.$role
				[ $USER = "root" ] && [ "$RETVAL" = "0" ] && [ -f /var/run/$prog.$role.pid ] && rm -f /var/run/$prog.$role.pid
				
			fi
		done	
   	        [ -f /var/lock/subsys/$prog.$role ] && rm -f /var/lock/subsys/$prog.$role
                       [ -f /var/run/$prog.$role.pid ] && rm -f /var/run/$prog.$role.pid
			[ "$RETVAL" = "0" ] && success || failure 	
		echo
	done
        return $GRETVAL
}

getstatus() {
        # Loop over xrootd roles
        for i in ${XRD_ROLES}; do
                # Check if the xrootd daemon associated to this role running
  	        status -p /var/run/$prog.$i.pid $prog.$i >& /dev/null
                pid=`pidofproc $prog.$i`
                if [ -n "$pid" ]; then
                        echo $"$prog for role: $i (pid $pid) is running..."
                        continue
                else
                        # See if /var/lock/subsys/$prog.$i exists
                        if [ -f /var/lock/subsys/$prog.$i ]; then
                                echo $"$prog for role: $i dead but subsys locked"
                                RETVAL=1
                        else
				pid=`ps -eo pid,ppid,comm,cmd | grep -v egrep | egrep "$prog -n $i"| awk '{print $1}' | head -1`
                                if [ -n "$pid" ]; then
                                   echo $"$prog for role: $i is starting (pid $pid) "
				   RETVAL=0
	 			else	
                                   echo $"$prog for role: $i is stopped"
                                   RETVAL=2
				fi
                        fi
                fi                        
        done

        if [ "$i" = "fed" ]; then
           /etc/rc.d/init.d/cmsd status
        fi

        return $RETVAL
}

condrestart() {
    if [ -z "$1" ]; then
        for i in ${XRD_ROLES}; do
            /etc/init.d/eos condrestart $i
            if [ "$i" = "fed" ]; then
               /etc/rc.d/init.d/cmsd condrestart
            fi
        done;
    else
        if [ -f /var/lock/subsys/$prog.$1 ]; then
            if [ "$i" = "fed" ]; then
               /etc/rc.d/init.d/cmsd restart
            fi
            restart $1;
        fi
    fi
}

restart() {
    if [ "$eoshaoff" = "1" ]; then
        /etc/init.d/eosha stop 
    fi
    if [ "$eosdoff" = "1" ]; then
        /etc/init.d/eosd stop 
    fi
    stop $1
    sleep 5  
    start $1
    if [ "$eoshaoff" = "1" ]; then
        /etc/init.d/eosha start 
    fi
    if [ "$eosdoff" = "1" ]; then
        /etc/init.d/eosd start 
    fi
}

# Determine the role
if [ -n "$2" ]; then
     	if [[ "$XRD_ROLES" =~ "$2" ]];  then
	     XRD_ROLES=$2
	     if [ "$XRD_ROLES" = "mgm" ]; then
   	     	XRD_ROLEFLAG="-m "
             fi
	else 
	     echo $"service $2 is not configured here"
	     exit 0
        fi	     

elif [ -z "${XRD_ROLES}" ]; then
        # No roles defined in the sysconfig file so lets automatically find out
        # which role we are. We assume we are a fst to begin with
        XRD_ROLES="fst"
	# New lets really see!
	if [ ! -f "${XRD_CONFIG}" ]; then
	        echo $"Failed to determine xrootd role - ${XRD_CONFIG}: No such file or directory"
		exit 1
	fi
	# Look for the all.manager entry in the xrd config file. If it has the 
        # hostname of the machine in it then this is a manager node
	grep `hostname -f` ${XRD_CONFIG} | grep "all.manager" > /dev/null
	if [ $? = "0" ]; then
	        XRD_ROLES="manager"
		XRD_USER=""
		XRD_ROLEFLAG="-m "
	fi

	grep `hostname -f` ${XRD_CONFIG} | grep "all.manager meta" > /dev/null
	if [ $? = "0" ]; then
	        XRD_ROLES="meta"
		XRD_USER=""
	fi

fi

eoshaoff=0
eosdoff=0

if [ -t 0 ]; then 
if [ -t 1 ]; then 
if [ "$1" != "status" ]; then
    /etc/init.d/eosha status 2>&1 | grep running >& /dev/null
    eoshastatus=$?
    /etc/init.d/eosd status 2>&1 | grep running >& /dev/null
    eosdstatus=$?
    if [ $eoshastatus = "0" ]; then
        if [ "$1" != "restart" ] && [ "$1" != "condrestart" ]; then 

            echo "Stop eosha to do that (service eosha stop) - you can do only restart while eosha is active"
            exit -1;
        else
            eoshaoff=1
        fi
    fi
    if [ $eosdstatus = "0" ]; then
	eosdoff=1
    fi	
fi
fi
fi

# See how we were called
case "$1" in

        start)
                start $2
                ;;
        stop)
                stop $2
                ;;
        status)
                getstatus
                ;;
        restart)
                restart $2
                ;;
        condrestart)
                condrestart $2
                ;;
        *)
                echo $"Usage: $0 {start|stop|status|restart|condrestart} [role]"
                exit 1
esac

exit $RETVAL
