#!/bin/bash

# default values, can be overridden by commandline options
CONFIGFILE=/etc/ntp.conf
CRYPTPW=""
KEYSDIR=/etc/ntp


MYVERSION=0.10

function show_usage {

	case "$1" in

			
		ak_tool)
			echo "ak_tool $MYVERSION: Available commands are:"
			echo ""
			echo "On a server machine (trusted NTP server):"
			echo "  server_create_pars [OPTIONS] "
			echo "     creates the necessary server parameters "
			echo "  server_create_groupkey [OPTIONS] CLIENTPWD"
			echo "     creates a groupkey for clients with client password CLIENTPWD"
			echo "  server_update_pars [OPTIONS] "
			echo "    updates the server parameters (they are only valid for 12 months)"
			echo ""
			echo "On a client machine:"
			echo "  client_create_pars [OPTIONS] "
			echo "    creates the necessary client parameters"
			echo "  client_install_groupkey [OPTIONS] SERVER GROUPKEYFILE"
			echo "    installs the groupkey file GROUPKEYFILE for your NTP server SERVER"
			echo "  client_update_pars [OPTIONS] "
			echo "    updates the client parameters (they are only valid for 12 months)"
			echo ""
			show_common_options
			;;
			
		server_create_pars)
			echo "server_create_pars $MYVERSION:"
			echo ""
			echo "Usage:"
			echo "         server_create_pars [OPTIONS]"
			echo ""
			echo "This is the first command you need to run on your trusted server. It"
			echo "generates the necessary server parameters used for the autokey mechanism."
			echo ""
			echo "Please note that these server parameters are only valid for 12 months and"
			echo "need to be updated on a regular basis by using the "
			echo "server_update_pars command."
			echo ""
		        show_common_options
			;;

		server_create_groupkey)
			echo "server_create_groupkey $MYVERSION:"
			echo ""
			echo "Usage:"
			echo "         server_create_groupkey [OPTIONS] CLIENTPWD"
			echo ""
			echo "You need to create a groupkey for each group of clients using the same"
			echo "client password (which has to be specified with the CLIENTPWD parameter)."
			echo "After you created the group key file (the name will be something like"
			echo "\"ntp_groupkey_YYYYMMDDHHMMSS\", where YYYYMMDDHHMMSS is replaced with a "
			echo "representation of the current date and time), you need to transfer it"
			echo "to your clients. Please make sure that you use a secure transfer "
			echo "mechanism such as scp or an encrypted mail, because the groupkey should"
			echo "be regarded as confidential information."
			echo ""
			show_common_options
			;;

		server_update_pars)
			echo "server_update_pars $MYVERSION:"
			echo ""
			echo "Usage:"
			echo "         server_update_pars [OPTIONS]"
			echo ""
			echo "Due to the fact that the server parameters are only valid for 1 year, it"
			echo "is required to update them on a regular basis, e.g. once per month."
			echo ""
			show_common_options
			;;

		client_create_pars)
			echo "client_create_pars $MYVERSION:"
			echo ""
			echo "Usage:"
			echo "         client_create_pars [OPTIONS]"
			echo ""
			echo "This is the first command you need to run on your client. It"
			echo "generates the necessary client parameters used for the autokey mechanism."
			echo ""
			echo "Please note that these client parameters are only valid for 12 months and"
			echo "need to be updated on a regular basis by using the "
			echo "client_update_pars command."
			echo ""
		        show_common_options
			;;

		client_install_groupkey)
			echo "client_install_groupkey $MYVERSION:"
			echo ""
			echo "Usage:"
			echo "         client_install_groupkey [OPTIONS] SERVER GROUPKEYFILE"
			echo ""
			echo "With this command you can install the groupkey file which has been created"
			echo "and transferred to the client (the name will be something like"
			echo "\"ntp_groupkey_YYYYMMDDHHMMSS\", where YYYYMMDDHHMMSS is replaced with a "
			echo "representation of the current date and time). You need to do this for each"
			echo "server for which you have specified the \"autokey\" flag in your ntp.conf file."
			echo "Please note that the \"installation\" will only create a symlink from the"
			echo "specified GROUPKEYFILE to a server-specific file in your keys directory, "
			echo "therefore the GROUPKEYFILE needs to remain where it is when running this"
			echo "command. And, of course, you should use absolute path names in order to avoid"
			echo "trouble."
			echo ""
			show_common_options
			;;

		client_update_pars)
			echo "client_update_pars $MYVERSION:"
			echo ""
			echo "Usage:"
			echo "         client_update_pars [OPTIONS]"
			echo ""
			echo "Due to the fact that the client parameters are only valid for 1 year, it"
			echo "is required to update them on a regular basis, e.g. once per month."
			echo ""
			show_common_options
			;;

		*)
			echo "NTP Autokey Key Management Tool ak_tool $MYVERSION"
			echo "========================================================="
			echo ""
			echo "Usage:"
			echo "  ak_tool command [parameters...] "
			echo ""
			echo "Please use the \"help\" command to list all available"
			echo "commands, e.g."
			echo "    ak_tool help"
			echo ""
			;;
	

		esac
		

}

function show_common_options {
			echo "Valid options are:"
			echo "  --cfgfile|-c CONFIGFILE  location of ntp.conf (default: /etc/ntp.conf)"
			echo "  --binpath|-b BINARYPATH  directory where the ntp-keygen binary can be found"
			echo "                           (default: using the shell PATH variable)"
			echo "  --cryptpw|-p PASSWORD    crypto password (default: the one specified in "
			echo "                           the ntp.conf file)"
			echo "  --keysdir|-k KEYSDIR     directory where the ntp keys are stored (default:"
			echo "                           specified in the ntp.conf file)"
			echo ""
}
			

function get_serverpasswd {
	CRYPTPW=""
	CRYPTPW=`cat $CONFIGFILE | egrep -v "^#" | grep "crypto pw " | cut -d" " -f3`
	if [ "$CRYPTPW" = "" ]; then
		return 1
 	fi	

	return 0
}

function get_keysdir {
	KEYSDIR=""
	KEYSDIR=`cat $CONFIGFILE | egrep -v "^#" | grep "keysdir " | cut -d" " -f2`
	if [ "$KEYSDIR" = "" ]; then
		return 1
	fi
	return 0
}


MYDIR=`dirname $0`
MYNAME=`basename $0`

if [ "$MYNAME" = "ak_tool" ]; then
	case "$1" in 
	"server_create_pars"|"server_update_pars"|"server_create_groupkey")
		MYNAME=$1
		shift
		;;
	"client_create_pars"|"client_update_pars"|"client_install_groupkey")
		MYNAME=$1
		shift
		;;
	"-h"|"-?"|"--help"|"help")
		show_usage ak_tool
		exit 0
		;;
	*)
		echo "ERROR: Unknown command $1" > /dev/stderr
		show_usage unknown 
		exit 3
		;;
	esac
fi

if [ "$MYNAME" == "" ]; then
	show_usage ak_tool
	exit 1
fi

ROLE=`echo $MYNAME | cut -d "_" -f 1`

while [ "$1" != "" ]; do

	case "$1" in
	
	"-?"|"--help"|"-h"|"help")	
		show_usage $MYNAME
		exit 1
		;;
	
	"--cfgfile"|"-c")
		shift
		CONFIGFILE=$1
		shift
		;;
		
	"--binpath"|"-b")
		shift
		BINARYPATH=$1
		shift
		;;
		
	"--keysdir"|"-k")
		shift
		KEYSDIR=$1
		shift
		;;
	
	"--cryptpw"|"-p")
		shift
		SRVPASSWD=$1
		shift
		;;
	
	*)
		case "$PARCOUNT" in

		"")
				PARCOUNT=1
				CLIENTPWD=$1
				shift
				;;
		"1")
				PARCOUNT=2
				GROUPKEY=$1
				shift
				;;
		
		*)
				PARCOUNT=$[${PARCOUNT} + 1]
				shift
				;;
		esac
			
		

	esac

done

# Parameter checks ...

if [ "$CONFIGFILE" = "" ]; then
	echo "ERROR: No configuration file specified!" > /dev/stderr
	exit 1
fi

if [ ! -e "$CONFIGFILE" ]; then
	echo "ERROR: The specified configuration file $CONFIGFILE was not found." > /dev/stderr
	exit 1
fi

if [ "$SRVPASSWD" = "" ]; then
	get_serverpasswd $CONFIGFILE
else
	CRYPTPW=$SRVPASSWD
fi

get_keysdir $CONFIGFILE


if [ "$CRYPTPW" = "" ]; then
	echo "ERROR: $ROLE password not set (on commandline and/or in configuration file!" > /dev/stderr
	exit 1
fi

if [ ! -d "$KEYSDIR" ]; then
	echo "ERROR: Specified keysdir $KEYSDIR was not found. Please create it and retry." > /dev/stderr
	exit 1
fi

echo "Using Configfile $CONFIGFILE and keysdir $KEYSDIR "

if [ "$BINARYPATH" = "" ]; then
	KEYGENTOOL=`which ntp-keygen`
	BINARYPATH=`dirname $KEYGENTOOL`
fi

if [ ! -e $BINARYPATH/ntp-keygen ]; then
	echo "ERROR: No ntp-keygen tool found at $BINARYPATH" > /dev/stderr
	exit 2
fi

CURRENT_DIR=`pwd`
cd $KEYSDIR


if [ "$MYNAME" = "server_create_groupkey" ]; then
	if [ "$CLIENTPWD" = "" ]; then
		echo "ERROR: You need to specify a client password in order to create a groupkey!" > /dev/stderr
		exit 1
	fi

	OUTPUTFILE=ntp_groupkey_`date +"%Y%m%d%H%M%S"`
	echo "Creating group key file $OUTPUTFILE:"
fi

if [ "$MYNAME" = "client_install_groupkey" ]; then
	if [ "$CLIENTPWD" = "" ]; then
		echo "ERROR: You need to specify the server hostname in order to install a groupkey!" >/dev/stderr
		exit 1
	fi

	if [ "$GROUPKEY" = "" ]; then
		echo "ERROR: No group key file specified." > /dev/stderr
		exit 1
	fi
	
	if [ ! -e "$GROUPKEY" ]; then
	   if [ -e "$KEYSDIR/$GROUPKEY" ]; then
	   	GROUPKEY="$KEYSDIR/$GROUPKEY"
	   else
		echo "ERROR: Specified group key $GROUPKEY not found." > /dev/stderr
		exit 3
	   fi
	fi

	echo "Installing group key $GROUPKEY in $KEYSDIR:"
	
fi

if [ "$MYNAME" = "client_update_pars" ]; then
	echo "Updating client parameters:"
fi

if [ "$MYNAME" = "server_update_pars" ]; then
	echo "Updating server parameters:"
fi


OK=""
if [ "$MYNAME" = "server_create_pars" ]; then
	echo "========= Invoking ntp-keygen ============"
	$BINARYPATH/ntp-keygen -T -I -p $CRYPTPW && OK=TRUE
elif [ "$MYNAME" = "server_create_groupkey" ]; then
	echo "========= Invoking ntp-keygen ============"
	$BINARYPATH/ntp-keygen -e -q $CRYPTPW -p $CLIENTPWD > $OUTPUTFILE && OK=TRUE
elif [ "$MYNAME" = "client_create_pars" ]; then
	echo "========= Invoking ntp-keygen ============"
	$BINARYPATH/ntp-keygen -H -p $CRYPTPW && OK=TRUE
elif [ "$MYNAME" = "client_install_groupkey" ]; then
	echo "========= Creating symlink ==============="
	ln -s $GROUPKEY ntpkey_iff_${CLIENTPWD} && OK=TRUE
elif [ "$MYNAME" = "client_update_pars" ]; then
	echo "========= Invoking ntp-keygen  ==============="
	$BINARYPATH/ntp-keygen -q $CRYPTPW && OK=TRUE
elif [ "$MYNAME" = "server_update_pars" ]; then
	echo "========= Invoking ntp-keygen  ==============="
	$BINARYPATH/ntp-keygen -T -q $CRYPTPW && OK=TRUE
fi


cd $CURRENT_DIR

if [ "$OK" != "TRUE" ]; then
	echo "ERROR: An error occured. Please check the above output."
	exit 3
fi

echo "======================== Done ================================="
if [ "$MYNAME" = "server_create_groupkey" ]; then
	echo "OK. Groupkey file $OUTPUTFILE has been created. Please transfer this file to "
	echo " your client(s) that use the specified client password. You need to create"
	echo " another groupkey for clients that use a different client password."
fi

