#!/bin/sh -e

##########################################################################
#   Script description:
#       Set up cluster firewall
#
#   Arguments:
#       head|io|compute|vis
#
#   History:
#   Date        Name        Modification
#   2018-08-15  J Bacon     Begin
##########################################################################

usage()
{
    printf "Usage: $0 head|backup|io|compute|vis\n"
    exit 1
}


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

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

case $(auto-ostype) in
RHEL)
    # Excellent firewalld tutorial:
    # https://www.digitalocean.com/community/tutorials/how-to-set-up-a-firewall-using-firewalld-on-centos-7#creating-your-own-zones
    
    # yum install firewalld Part of CentOS base?
    
    # Basic checks
    systemctl enable firewalld
    systemctl start firewalld
    firewall-cmd --state
    firewall-cmd --get-default-zone
    firewall-cmd --get-active-zones
    firewall-cmd --list-all
    
    # Default zone is public, be more permissive?
    # firewall-cmd --list-all-zones
    # firewall-cmd --set-default-zone=home
    # firewall-cmd --get-services
    
    # Trust all cluster nodes
    # firewall-cmd --permanent --add-source=192.168.0.0/16
    firewall-cmd --permanent --direct \
	--add-rule ipv4 filter INPUT_direct 0 -s 192.168.0.0/16 -j ACCEPT
    
    node_type=$1
    case $node_type in
    head|backup)
	# Allow http traffic from outside the cluster
	firewall-cmd --permanent --add-service=http
	firewall-cmd --permanent --add-service=tftp
	firewall-cmd --permanent --list-services
	firewall-cmd --zone=public --list-ports
	
	# If we want to add special ports
	
	# NFS
	firewall-cmd --permanent --add-service=mountd
	firewall-cmd --permanent --add-service=rpc-bind
	firewall-cmd --permanent --add-service=nfs
	
	# SLURM
	firewall-cmd --permanent --add-port=6817/udp    # slurmctld
	firewall-cmd --permanent --add-port=6817/tcp    # slurmd
	;;
    
    compute)
	# SLURM
	firewall-cmd --permanent --add-port=6817/udp    # slurmctld
	firewall-cmd --permanent --add-port=6817/tcp    # slurmd
	;;
    
    io)
	# NFS
	firewall-cmd --permanent --add-service=mountd
	firewall-cmd --permanent --add-service=rpc-bind
	firewall-cmd --permanent --add-service=nfs
	;;
    
    vis)
	;;
    
    *)
	printf "Unknown node type: $node_type\n"
	exit 1
	;;
    
    esac
    
    firewall-cmd --reload
    firewall-cmd --list-all
    ;;

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

esac
