#!/bin/sh

#
# Handle args
#

usage() {
cat <<EOF
$0 [OPTION]
  -b, --basedir  Base of ltsp chroot.  Default is /opt/ltsp if unspecified.
  -e, --export   Export ssh key file.  Default is 
                 \${basedir}/etc/ssh/ssk_known_hosts if unspecified.
  -h, --help     This message.
EOF
}

ARGS=$(getopt -o b:e:h --long base:,export:,help -n $0 -- "$@")

[ $? != 0 ] && exit 1

eval set -- "${ARGS}"

while true ; do
    case "$1" in
        -b|--base)   BASE=$2 ; shift 2 ;;
        -e|--export) EXPORTFILE=$2 ; shift 2 ;;
        -h|--help)   usage ; exit 0 ;; 
        --) shift ; break ;;
        *) echo "Internal error!" ; exit 1 ;;
    esac
done

# Set up variables
BASE=${BASE:-"/opt/ltsp"}
if [ -z "${CHROOTS}" ]; then
    CHROOTS=$(find ${BASE} -mindepth 1 -maxdepth 1 -type d 2>/dev/null | \
              grep -v images)
fi
HOSTNAME=$(hostname)
IPS=$(ip -o -f inet addr show | sed -e 's,.* \(.*\)/.*,\1,' | grep -v '^127')
OUTPUT=$(mktemp)
ENC="dsa rsa"
NAMES="${HOSTNAME} ${IPS}"
LOGFILE="/var/log/syslog"

# Any chroots found?
if [ -z "${CHROOTS}" ]; then
	logger -f $LOGFILE -t ltsp \
        "No client chroots found, please run ltsp-build-client"
	exit 0
fi

# Get encryption keys
for NAME in ${NAMES}; do
    for ENCRYPTION in ${ENC}; do
		if [ -f /etc/ssh/ssh_host_${ENCRYPTION}_key.pub ]; then
			echo $(echo $NAME $(cat /etc/ssh/ssh_host_${ENCRYPTION}_key.pub | \
                awk '{split ($0, a, " "); print a[1]" "a[2]" "}')) >> $OUTPUT
			logger -f $LOGFILE -t ltsp \
                "# Creating ${ENCRYPTION}-hostkey for ${NAME}"
		else
			logger -f $LOGFILE -t ltsp \
                "No ${ENCRYPTION} key found for ${NAME}, please configure \
                 your ssh server correctly"
		fi
    done
done

# Add any additional hosts
for SSHHOST in $(ls /etc/ltsp/ssh_known_hosts.* 2> /dev/null); do
    cat ${SSHHOST} >> $OUTPUT
done

#
# export file
# We need this for multiple host support.  This way, we can do an
# ltsp-update-sshkeys --export ssh_known_hosts.myname
# and install this file in the /etc/ltsp dir, where it will be picked up
# by the above.
# Note that ltsp-update-sshkeys --export - cats to stdout
# If no export specified, then update local chroots.
#

if [ -n "${EXPORTFILE}" ]; then
    if [ "${EXPORTFILE}" = "-" ]; then
        cat ${OUTPUT}
    else
        install -m 644 ${OUTPUT} ${EXPORTFILE}
    fi
else
    for CHROOT in ${CHROOTS}; do
        if [ -d ${CHROOT}/etc/ssh ]; then
            install -m 644 $OUTPUT ${CHROOT}/etc/ssh/ssh_known_hosts
        else
            echo "WARNING: ${CHROOT}/etc/ssh not found. skipping..."
        fi
    done
fi

rm -f ${OUTPUT}

exit 0
