#!/usr/bin/bash

# Get updated system information, including SSH keys and network devices,
# and generate an issue to display before login.

# Copyright (c) 2019 Fedora CoreOS Authors. All rights reserved.
# Copyright (c) 2013 The CoreOS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# Modified from the CoreOS repository:
#  * https://github.com/coreos/init/blob/master/scripts/issuegen
#  * https://github.com/coreos/init/blob/master/scripts/sshd_keygen

set -e

PKG_NAME=console-login-helper-messages
ISSUE_DIR_PUBLIC=issue.d
ISSUE_DIR_PRIVATE=${PKG_NAME}/issue.d
# TODO: it would be nice to have /run/issue.d be an official directory,
#       see https://github.com/karelzak/util-linux/commit/1fc82a1360305f696dc1be6105c9c56a9ea03f52#commitcomment-27949895
#       until then, $GENERATED_ISSUE writes to the privately scoped directory (not in /run/issue.d)
GENERATED_ISSUE=/run/${PKG_NAME}/${PKG_NAME}.issue
SSH_DIR=/etc/ssh

# The public directories are to be read by higher-level programs to display
# the issue on login, e.g. agetty.
# The private directories are to be read only by this script.
mkdir -p ${SSH_DIR}
mkdir -p /run/${ISSUE_DIR_PUBLIC}
mkdir -p /run/${ISSUE_DIR_PRIVATE}
rm -f ${GENERATED_ISSUE}
touch ${GENERATED_ISSUE}

echo "This is \n (\s \m \r) \t" > ${GENERATED_ISSUE}

# Provide key fingerprints via issue
for KEY_FILE in $(find ${SSH_DIR} -name 'ssh_host_*_key') ; do
	ssh-keygen -l -f ${KEY_FILE}
done | awk '{print "SSH host key: " $2 " " $4}' > "/run/${ISSUE_DIR_PRIVATE}/21_ssh_host_keys.issue"

# Data from udev rules
case "$1" in
	add)
		echo "${2}: \\4{${2}} \\6{${2}}" > "/run/${ISSUE_DIR_PRIVATE}/22_${2}.issue"
		;;
	remove)
		rm -f "/run/${ISSUE_DIR_PRIVATE}/${2}"
		;;
esac

if [[ -d "/etc/${ISSUE_DIR_PRIVATE}" ]]; then
	cat /etc/${ISSUE_DIR_PRIVATE}/* 2>/dev/null >> ${GENERATED_ISSUE} || true
fi
if [[ -d "/run/${ISSUE_DIR_PRIVATE}" ]]; then
	cat /run/${ISSUE_DIR_PRIVATE}/* 2>/dev/null >> ${GENERATED_ISSUE} || true
fi
if [[ -d "/usr/lib/${ISSUE_DIR_PRIVATE}" ]]; then
	cat /usr/lib/${ISSUE_DIR_PRIVATE}/* 2>/dev/null >> ${GENERATED_ISSUE} || true
fi

echo >> ${GENERATED_ISSUE}
