#!/bin/bash
#
# /usr/NX/bin/nxkeygen
#		Create a new client/server key pair
#
#		Originally written for Gentoo Linux
#
# Author	Stuart Herbert
#		(stuart@gentoo.org)
#
# Copyright	(c) 2004 Gentoo Foundation
#		Released under v2 of the GNU GPL
#
# ========================================================================

# Get NX_ configuration variables
export PATH=$PATH:$(cd $(dirname $0) && pwd)
export $(grep ^NX_ $(which nxserver))

NX_KEY_DIR="$NX_HOME_DIR/.ssh"
DATE="`date '+%Y%m%d-%H%M%S'`"
NX_CLIENT_KEY="${NX_KEY_DIR}/client.id_dsa.key"
NX_SERVER_KEY="${NX_KEY_DIR}/server.id_dsa.pub.key"

main ()
{
	# create a new key
	umask 002
	ssh-keygen -q -t dsa -N '' -f ${NX_KEY_DIR}/local.id_dsa

	# backup the existing keys
	
	if [ -f "${NX_SERVER_KEY}" ]; then
		echo "Backing up existing server key to ${NX_SERVER_KEY}.${DATE}"
		mv -f "${NX_SERVER_KEY}" "${NX_SERVER_KEY}.${DATE}"
	fi

	if [ -f "${NX_CLIENT_KEY}" ]; then
		echo "Backing up existing client key to ${NX_CLIENT_KEY}.${DATE}"
		mv -f "${NX_CLIENT_KEY}" "${NX_CLIENT_KEY}.${DATE}"
	fi

	# put the new keys in place

	mv -f "${NX_KEY_DIR}/local.id_dsa" "${NX_CLIENT_KEY}"
	mv -f "${NX_KEY_DIR}/local.id_dsa.pub" "${NX_SERVER_KEY}"

	for x in ${NX_CLIENT_KEY} ${NX_SERVER_KEY} ; do
		chmod 600 $x
		chown nx:root $x
	done
	
	# copy the key to the authorized_keys2 file
	cp -af ${NX_SERVER_KEY} $NX_HOME_DIR/$NX_AUTHORIZED_KEYS_FILE

	# now tell the user what to do

	echo "Unique key generated; your users must install"
	echo
	echo "    ${NX_CLIENT_KEY}"
	echo
	echo "on their computers."
}

main "$@"

