#!/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"
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}"

# 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 "${ACTION}" in
	add)
		echo "${INTERFACE}: \\4{${INTERFACE}} \\6{${INTERFACE}}" > "/run/${ISSUE_DIR_PRIVATE}/22_${INTERFACE}.issue"
		;;
	remove)
		rm -f "/run/${ISSUE_DIR_PRIVATE}/22_${INTERFACE}.issue"
		;;
esac

# 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)
#
# Pick 40 as an index as other files can order around it easily.
generated_file="/run/${PKG_NAME}/40_${PKG_NAME}.issue"
generated_string=''
# Hack around files potentially not existing in the below paths with `|| true`.
generated_string+=$(cat /etc/${ISSUE_DIR_PRIVATE}/* 2>/dev/null || true)
generated_string+=$(cat /run/${ISSUE_DIR_PRIVATE}/* 2>/dev/null || true)
generated_string+=$(cat /usr/lib/${ISSUE_DIR_PRIVATE}/* 2>/dev/null || true)

echo "${generated_string}" > "${generated_file}"
