#!/bin/sh
#
# Maximilian Wilhelm <max@rfc2324.org>
#  --  Mon 31 Aug 2015 08:55:27 AM CEST
#

if [ $# -lt 1 ]; then
	echo "Usage: $(basename $0) [ -c ] fastd_instance | -a" >&2
	exit 1
fi

fastd_ciphers () {
	socket_path=$(grep "status socket" "/etc/fastd/${1}/fastd.conf" | grep -o '/[0-9a-z/_.-]\+')

	echo -n "$1: "
	socat - "UNIX-CONNECT:${socket_path}" | jq '.peers[] | select (.connection) | .connection | .method ' | sort | uniq -c
}

fastd_con () {
	socket_path=$(grep "status socket" "/etc/fastd/${1}/fastd.conf" | grep -o '/[0-9a-z/_.-]\+')

	echo -n "$1: "
	socat - "UNIX-CONNECT:${socket_path}" | jq '.peers[] | select( .connection ) | .name' | wc -l
}

mode="count"
if [ "${1}" = "-c" ]; then
	mode="ciphers"
	shift
fi

instances="${@}"
if [ "${1}" = "-a" ]; then
	instances="all"
fi


# Verify existance of fastd instance
if [ "$instances" != "all" -a ! -d "/etc/fastd/${instances}" ]; then
	echo "Invalid fastd instance \"$instances\"." >&2
	exit 1

# Figure out all fastd instances
elif [ "$instances" = "all" ]; then
	instances=$(find /etc/fastd -mindepth 1 -maxdepth 1 -type d  -exec basename {} \; | sort)
	
	if [ ! "${instances}" ]; then
		echo "Did not find any configured instances in /etc/fastd." >&2
		exit 1
	fi
fi


for inst in ${instances}; do
	if [ "${mode}" = "count" ]; then
		fastd_con ${inst}

	elif [ "$mode" = "ciphers" ]; then
		fastd_ciphers ${inst}
	fi
done