#!/bin/bash
# Copyright (c) 2016 Alba Synchrotron, Barcelona, Spain.
# All rights reserved.
#
# Author: Sergi Pusó
#
# LSB compatible service control script; see http://www.linuxbase.org/spec/
#

### BEGIN INIT INFO
# Provides:          sicilia
# Required-Start:    $syslog $remote_fs
# Should-Start:
# Required-Stop:
# Should-Stop:
# Default-Start:     3 5
# Default-Stop:
# X-Start-Before:    tango-starter
# Description:       Start the sicilia environment for Controls machines.
#       This script should allow performing some common privileged tasks
#       like loading hardware drivers or setting a pattern for core files.
### END INIT INFO
#

#Load all the Sicilia environment variables first
. /etc/profile.d/sicilia.sh


case "$1" in
    start)
        # Setup a folder for core dumps
        if ! test -e /tmp/corefiles ; then
            mkdir /tmp/corefiles
        fi
        chmod 777 /tmp/corefiles

        # Set the default pattern for core dumps
        echo "/tmp/corefiles/core.%u.%h.%e.%p" > /proc/sys/kernel/core_pattern

        # Add tangosys to extra groups (i.e: mrftiming for /dev/era, uucp for /dev/ttyR...) if they exist
        TANGOSYS_EXTRA_GROUPS="mrftimingsys uucp"
        for extragroup in $TANGOSYS_EXTRA_GROUPS
        do
                groupmembers=`grep "^$extragroup:" /etc/group`
                if [ -n "$groupmembers" ]
                then
                        if [[ $groupmembers != *"tangosys"* ]]
                        then
                                /bin/logger -s -t sicilia "sicilia: adding tangosys to grup $extragroup"
                                usermod -a -G $extragroup tangosys
                        fi
                fi
        done

	# Create wireshark group for running it non-root from sicilia(req. by sblanch, 21-04-2016)
        if [ -f /usr/bin/wireshark ] && ! grep -q '^wireshark:x:.*sicilia' /etc/group
        then
                /bin/logger -s -t sicilia "sicilia: creating wireshark group and adding sicilia"
                groupadd -r wireshark
                usermod -a -G wireshark sicilia
                chgrp wireshark /usr/bin/dumpcap
                chmod 4750 /usr/bin/dumpcap
        fi


        # Run the loaddrivers.sh which calls the loaders for all the drivers this
        # specific machine will need. Each loader basically loads the kernel module
        # using insmod plus some other tasks like mknod's, reading conf parameters, etc..
        if [ -f $SICILIALOCAL/loaddrivers.sh ];
        then
                $SICILIALOCAL/loaddrivers.sh   | /bin/logger -s -t loaddrivers
        fi


        # Any initialization code for all diskless OSs should also go here

        ;;
    stop)
        # Perform any shutdown tasks here
        ;;
esac
