#!/bin/sh -e

##########################################################################
#   Script description:
#       Enable munge service
#       
#   History:
#   Date        Name        Modification
#   2013-12-26  J Bacon     Begin
##########################################################################

usage()
{
    printf "Usage: $0 node-type\n"
    exit 1
}


##########################################################################
#   Function description:
#       Pause until user presses return
##########################################################################

pause()
{
    local junk
    
    printf "Press return to continue..."
    read junk
}


##########################################################################
#   Main
##########################################################################

if [ $# != 1 ]; then
    usage
fi

NODE_TYPE=$1

case $(auto-ostype) in
RHEL)
    # FIXME: Use auto-os-release and support RHEL 8
    if fgrep 'release 6' /etc/redhat-release; then
	RHEL_VERSION=6
    else
	RHEL_VERSION=7
    fi
    
    LOCALBASE=$(cluster-localbase)
    munge_etc="$LOCALBASE/etc/munge"
    mkdir -p -m 0700 $munge_etc
    
    case $NODE_TYPE in
    'head')
	if [ ! -e $munge_etc/munge.key ]; then
	    printf "Generating munge key...\n"
	    dd if=/dev/urandom bs=1 count=1024 > $munge_etc/munge.key
	    chmod 600 $munge_etc/munge.key
	fi
	;;
    
    'compute')
	if [ ! -e $munge_etc/munge.key ]; then
	    printf "Error, missing munge key.  Should have been pushed over by cluster-sync-node.\n"
	    exit
	fi
	;;
    
    *)
	printf "$0 is only for head and compute nodes.\n"
	exit 1
	;;
    esac
    
    # https://github.com/dun/munge/wiki/Installation-Guide
    # FIXME: Move this to munge pkg?
    mkdir -p -m 711 $LOCALBASE/var/lib/munge
    mkdir -p -m 700 $LOCALBASE/var/log/munge
    mkdir -p -m 755 $LOCALBASE/var/run/munge
    mkdir -p -m 400 $munge_etc
    
    chmod 755 $LOCALBASE/var/lib $LOCALBASE/var/log $LOCALBASE/var/run
    chown -Rh daemon:daemon \
	$LOCALBASE/var/log/munge \
	$LOCALBASE/var/run/munge \
	$LOCALBASE/var/lib/munge \
	$munge_etc
    
    # RHEL init script
    case $RHEL_VERSION in
    6)
	rm -f /etc/init.d/munge
	init_script=$LOCALBASE/share/examples/rc.d/init.d/munge
	if [ -e $init_script ]; then
	    ln -s $init_script /etc/init.d/munge
	fi
	chkconfig munge on
	service munge restart
	;;
    
    7)
	init_script=$LOCALBASE/lib/systemd/system/munge.service
	# FIXME: Move this to munge pkg?
	sed -i'' 's|=munge|=daemon|g' $init_script
	systemctl disable munge.service || true
	systemctl enable $init_script || true
	systemctl daemon-reload
	systemctl restart munge.service
	;;
    
    *)
	printf "$0: Not supported on $RHEL_VERSION.\n"
	exit 1
	;;

    esac
    ;;

*)
    printf "$0: Not supported on $(auto-ostype).\n"
    exit 1
    ;;

esac
