#! /bin/sh
# show key for this host, in DNS format
# Copyright (C) 2000  Henry Spencer.
# 
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 2 of the License, or (at your
# option) any later version.  See <http://www.fsf.org/copyleft/gpl.txt>.
# 
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
# or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
# for more details.
#
# RCSID $Id: showhostkey,v 1.1 2000/04/15 23:37:53 henry Exp $

file=/etc/ipsec.secrets
me="ipsec showhostkey"

if test ! -f $file
then
	echo "$me: file \`$file' does not exist" >&2
	exit 1
elif test ! -r $file
then
	echo "$me: permission denied (cannot read \`$file')" >&2
	exit 1
fi

host="`hostname --fqdn`."

awk '	BEGIN {
		good = 0
		seengood = 0
		nfound = 0
		err = "cat >&2"
		me = "'"$me"'"
		host = "'"$host"'"
		file = "'"$file"'"
		status = 0
	}
	/^:[ \t]+RSA[ \t]+{$/ {
		good = 1
		seengood = 1
	}
	/^[ \t]+}$/ {
		good = 0
	}
	good && $0 ~ /^[ \t]+#IN[ \t]+KEY[ \t]+/ {
		out = $0
		sub(/^[ \t]+#IN[ \t]+KEY[ \t]+/, "\tIN\tKEY\t", out)
		nfound++
	}
	function grump(s) {
		print me ": " s |err
		status = 1
	}
	END {
		if (!seengood)
			grump("no key information in \"" file "\"")
		else if (nfound == 0)
			grump("no IN KEY line found -- key information old?")
		else if (nfound > 1)
			grump("multiple host keys found!?!")
		else
			print host out
		exit(status)
	}' $file
