#!/bin/bash
##############################################################################
# Copyright (c) Members of the EGEE Collaboration. 2004.
# See http://www.eu-egee.org/partners/ for details on the copyright
# holders.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS
# OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
##############################################################################
#
# NAME :        config_DPM_se
#
# DESCRIPTION : This function configures the SE
#
# AUTHORS :     David.Smith@cern.ch, Gergely.Debreczeni@cern.ch
#
# YAIM MODULE:  glite-yaim-dpm
#
##############################################################################

config_DPM_se_check () {
 
 requires $1 MY_DOMAIN VOS USERS_CONF DPM_HOST DPMFSIZE
 retcode=$?

 # Either DPMPOOL or DPM_FILESYSTEMS have to be defined
 if [ -z "$DPM_FILESYSTEMS" ] && [ -z "$DPMPOOL" ]; then
   yaimlog ERROR "DPMPOOL nor DPM_FILESYTEMS are defined!"
   retcode=1
 fi

 # Check length of the pools
 if [ -n "$DPMPOOL" ]; then
   charnum=`echo $DPMPOOL | wc -c`
   if [ $charnum -gt 15 ]; then
     yaimlog ERROR "The name of the DPM pool ($DPMPOOL) must be shorter than 15 character!"
     retcode=1
   fi
 fi

 for fs_entry in $DPM_FILESYSTEMS; do
   pool=`echo $fs_entry | awk -F: '{if ($3) print $1}'`
   if [ -n "$pool" ]; then
     charnum=`echo $pool | wc -c`
     if [ $charnum -gt 15 ]; then
       yaimlog ERROR "The name of the DPM pool ($fs_entry) must be shorter than 15 character!"
       retcode=1
     fi
   fi
 done

 unset charnum

 return ${retcode}
}

config_DPM_se () {


INSTALL_ROOT=${INSTALL_ROOT:-/opt}		
DPMCONFIG=${LCG_LOCATION}/etc/DPMCONFIG 
NSCONFIG=${LCG_LOCATION}/etc/NSCONFIG 
DPNS_BASEDIR=${DPNS_BASEDIR:-home}

####@ Hack to be removed when VOMS or YAIM CORE provides this !
if [ `uname -m` = 'x86_64' ]; then
        if [ `grep -c ^${GLITE_LOCATION}/lib64 /etc/ld.so.conf` = 0 ]; then
                echo "${GLITE_LOCATION}/lib64" >> /etc/ld.so.conf
                /sbin/ldconfig
        fi
else
        if [ `grep -c ^${GLITE_LOCATION}/lib /etc/ld.so.conf` = 0 ]; then
                echo "${GLITE_LOCATION}/lib" >> /etc/ld.so.conf
                /sbin/ldconfig
        fi
fi


check_users_conf_format

####@ Write sysconfig file of dpns, dpm, srmv1, srmv2, srmv2.2, dpmcopy daemons and restart them.

for x in dpns dpm srmv1 srmv2 srmv2.2 dpmcopy ; do
	xd=$x;
	if [ "$x" = "dpns" ]; then
		xd="dpnsdaemon"
	fi
	if [ "$x" = "dpmcopy" ]; then
		xd="dpmcopyd"
	fi

	####@ Create sysconfig file from template if it doesn't exist

	if [ ! -f /etc/sysconfig/$xd ]; then
		cp /etc/sysconfig/${xd}.templ /etc/sysconfig/$xd
	fi

	grep -v -E 'DPNS_HOST|DPM_HOST|CONFIGFILE' /etc/sysconfig/$xd > /etc/sysconfig/$xd+
	mv -f /etc/sysconfig/$xd+ /etc/sysconfig/$xd
	echo "export DPNS_HOST=${DPM_HOST}" >> /etc/sysconfig/$xd
	echo "export DPM_HOST=${DPM_HOST}"  >> /etc/sysconfig/$xd
	if [ "$x" = "dpns" ]; then
		echo NSCONFIGFILE=${NSCONFIG} >> /etc/sysconfig/$xd
	else
		echo DPMCONFIGFILE=${DPMCONFIG} >> /etc/sysconfig/$xd
	fi


    grep -q '^[^#]*ORACLE_HOME' /etc/sysconfig/$xd
    oracle_home_set=$?
    if [ $oracle_home_set -ne 0 ]; then
        echo ORACLE_HOME=${ORACLE_HOME} >> /etc/sysconfig/$xd
    fi

	####@ Temporary fix in case RUN_xxxDAEMON="yes" is missing from the existing sysconfig file
	
	if [ "x${x}x" == "xsrmv2.2x" ]; then
		upperx="SRMV2"
	else
		upperx=`echo $x | tr 'a-z' 'A-Z'`
	fi
	runmissing=`grep RUN_${upperx}DAEMON /etc/sysconfig/${xd}`
	if [ "x${runmissing}x" == "xx" ]; then
        	echo "RUN_${upperx}DAEMON=\"yes\"" >> /etc/sysconfig/${xd}
	fi

	####@ End of temporary fix

	/sbin/service $xd stop

	runtest="if [ \"x\${RUN_${upperx}DAEMON}\" = \"xyes\" ]; then exit 1; else exit 0; fi;"
	( . /etc/sysconfig/${xd}; eval $runtest )
	runset=$?
	if [ "x${x}" = "xsrmv2" -a $runset -ne 0 ]; then
		yaimlog INFO "The srmv2 daemon will be restarted, as it was previously conifgured to run, but"
		yaimlog INFO "the new default for a DPM installation is not to run it. It can be disabled by"
		yaimlog INFO "editing the value of RUN_SRMV2DAEMON in /etc/sysconfig/srmv2 and then"
		yaimlog INFO "/sbin/service srmv2 stop; /sbin/chkconfig srmv2 off"
	fi

	pid="X"
	while [ "x$pid" != "x" ]; do
		sleep 1s
		pid=`ps h -o pid -C $xd | awk '{print $1}'`
	done
	if [ $runset -ne 0 ]; then
		/sbin/service $xd start
		if [ $? -ne 0 ]; then
		  yaimlog ERROR "Could not start the $xd daemon"
		  return 1
		fi
		/sbin/chkconfig $xd on
	else
		/sbin/chkconfig $xd off
	fi
	sleep 1s
done

export DPNS_HOST=$DPM_HOST
export DPM_HOST=$DPM_HOST

####@ Adds the DPMPOOL to the pools.

if [ -n "$DPMPOOL" ]; then
    yaimlog DEBUG "Adding pool $DPMPOOL"
    ${LCG_LOCATION}/bin/dpm-addpool --poolname $DPMPOOL --def_filesize $DPMFSIZE
fi

for fs_entry in $DPM_FILESYSTEMS; do
    pool=`echo $fs_entry | awk -F: '{if ($3) print $1}'`
    if [ -n "$pool" ]; then
        yaimlog DEBUG "Adding pool $pool"
        ${LCG_LOCATION}/bin/dpm-addpool --poolname $pool --def_filesize $DPMFSIZE
    fi
done

####@ Created the default directory structure.
####@ The /dpm/${MY_DOMAIN}/${DPNS_BASEDIR} path is created per default.

if ( ! ${LCG_LOCATION}/bin/dpns-ls /dpm > /dev/null 2>&1 ); then
    ${LCG_LOCATION}/bin/dpns-mkdir /dpm
fi

if ( ! ${LCG_LOCATION}/bin/dpns-ls /dpm/${MY_DOMAIN} > /dev/null 2>&1 ); then
    ${LCG_LOCATION}/bin/dpns-mkdir -m 755 -p /dpm/${MY_DOMAIN}
fi

if ( ! ${LCG_LOCATION}/bin/dpns-ls /dpm/${MY_DOMAIN}/${DPNS_BASEDIR} > /dev/null 2>&1 ); then
    ${LCG_LOCATION}/bin/dpns-mkdir -m 755 -p /dpm/${MY_DOMAIN}/${DPNS_BASEDIR}
fi

####@ Sets the correct permissions on these directories.

${LCG_LOCATION}/bin/dpns-chmod 775 /dpm
${LCG_LOCATION}/bin/dpns-chmod 775 /dpm/${MY_DOMAIN}
${LCG_LOCATION}/bin/dpns-chmod 775 /dpm/${MY_DOMAIN}/${DPNS_BASEDIR}

${LCG_LOCATION}/bin/dpns-setacl -m d:u::7,d:g::7,d:o:5 /dpm
${LCG_LOCATION}/bin/dpns-setacl -m d:u::7,d:g::7,d:o:5 /dpm/${MY_DOMAIN}
${LCG_LOCATION}/bin/dpns-setacl -m d:u::7,d:g::7,d:o:5 /dpm/${MY_DOMAIN}/${DPNS_BASEDIR}

yaimlog DEBUG "Now creating default home directories for VOs"
for vo in `echo $VOS | tr '[:upper:]' '[:lower:]'`; do
    yaimlog DEBUG "Home for VO $vo"
    if ( ! ${LCG_LOCATION}/bin/dpns-ls /dpm/${MY_DOMAIN}/${DPNS_BASEDIR}/$vo > /dev/null 2>&1 ); then
            ${LCG_LOCATION}/bin/dpns-mkdir -m 775 /dpm/${MY_DOMAIN}/${DPNS_BASEDIR}/$vo
    fi
    ${LCG_LOCATION}/bin/dpns-chmod 775 /dpm/${MY_DOMAIN}/${DPNS_BASEDIR}/$vo
    ${LCG_LOCATION}/bin/dpns-entergrpmap --group $vo > /dev/null 2>&1
    ${LCG_LOCATION}/bin/dpns-chown root:$vo /dpm/${MY_DOMAIN}/${DPNS_BASEDIR}/$vo
    ${LCG_LOCATION}/bin/dpns-setacl -m d:u::7,d:g::7,d:o:5 /dpm/${MY_DOMAIN}/${DPNS_BASEDIR}/$vo
done

####@ Writes a cronjob (create-default-dirs-DPM.sh) to /etc/cron.monthly
####@ which will create the 'generated' directories one month in advance.

cd /etc/cron.monthly/
rm -f create-default-dirs-DPM.sh

cat << EOF > create-default-dirs-DPM.sh
export DPNS_HOST="$DPNS_HOST"
export DPM_HOST="$DPM_HOST"
VOS="${VOS}"
MYDOMAIN="${MY_DOMAIN}"
LCG_LOCATION="${LCG_LOCATION}"
DPNSBASEDIR="${DPNS_BASEDIR}"
EOF

cat <<'EOF' >> create-default-dirs-DPM.sh
for i in `seq 0 62`; do
 for vo in `echo $VOS | tr '[:upper:]' '[:lower:]'`; do
     mydate=`date +%Y-%m-%d -d "+$i days"`
     mypath="/dpm/$MYDOMAIN/${DPNSBASEDIR}/$vo/generated/$mydate"
     mygenpath="/dpm/$MYDOMAIN/${DPNSBASEDIR}/$vo/generated/"
     echo "Creating and setting correct permissions on: $mypath"
     ${LCG_LOCATION}/bin/dpns-mkdir -p ${mypath}
     ${LCG_LOCATION}/bin/dpns-chmod 775 ${mypath}
     ${LCG_LOCATION}/bin/dpns-chown root:$vo ${mypath}
     ${LCG_LOCATION}/bin/dpns-setacl -m d:u::7,d:g::7,d:o:5 ${mypath}
     ${LCG_LOCATION}/bin/dpns-chmod 775 ${mygenpath}
     ${LCG_LOCATION}/bin/dpns-chown root:$vo ${mygenpath}
     ${LCG_LOCATION}/bin/dpns-setacl -m d:u::7,d:g::7,d:o:5 ${mygenpath}
 done
done
EOF

chmod +x /etc/cron.monthly/create-default-dirs-DPM.sh

yaimlog INFO "IMPORTANT: A cron job has been installed: /etc/cron.monthly/create-default-dirs-DPM.sh"
yaimlog INFO "IMPORTANT: Run it manually this time (may take quite a while), in order to create the 'generated' directories for the VOs with the correct permission"
yaimlog INFO "IMPORTANT: This is to ensure that the whole VO is able to write in those directories."
yaimlog INFO "IMPORTANT: The script will run once a month and create the directories for the current and the next month."


return 0

}

