#!/bin/bash

TYPES="mgmt_nodes meta_nodes storage_nodes"

BEEGFS_PROC_DIR="/proc/fs/beegfs"
ESTABLISH_CONNS_CMD="df -t beegfs"

print_usage()
{
	echo
	echo "DESCRIPTION: Show all network connections that are currently established from"
	echo "this client to the BeeGFS servers."
	echo "(This script reads information from ${BEEGFS_PROC_DIR}.)"
	echo
	echo "NOTE: BeeGFS clients establish connections on demand and also drop idle"
	echo "connections after some time, so it does not automatically indicate an error if"
	echo "there is no connection currently established to a certain server."
	echo
	echo "USAGE: `basename $0` [options]"
	echo
	echo "   -h        - Print this help."
	echo
	echo "   -n        - No \"df\". By default, this script calls the \"df\" command to"
	echo "               force the client module to establish storage server connections,"
	echo "               but this can block if a storage server is unreachable."
	echo
}


################# end of function definitions ####################


# parse command line arguments

while getopts "hn" opt; do
        case $opt in
	h)
		print_usage
		exit 0
		;;
	n)
		SKIP_DF="1"
		;;
	*)
		echo "Invalid option: -$OPTARG" >&2
		print_usage
		exit 1
		;;
	esac
done

# call "df" to establish storage server connections

if [ -z "$SKIP_DF" ]; then
	out=`$ESTABLISH_CONNS_CMD`

	if [ -z "$out" ]; then
	echo "No active BeeGFS mounts found." >&2
	exit 1
	fi
fi

echo

# walk all client ID subdirs of beegfs proc dir

FIRST_LOOP="1"

for id in ${BEEGFS_PROC_DIR}/*; do
	if [ "${id}" = "${BEEGFS_PROC_DIR}/*" ]; then
		echo "No active BeeGFS mounts found." >&2
		exit 1
	fi

	# print separator for different mounts (starting with second mount loop)

	if [ -z "$FIRST_LOOP" ]; then
		echo
		echo "           ###################"
		echo
	fi

	# show contents of conns file for each server type

	for type in $TYPES; do
		echo "$type"
		echo "============="
		cat ${id}/${type} | grep -v "Root"
		echo
	done

	FIRST_LOOP=""
done

echo
