#!/bin/sh

# Copyright (C) 2025-2026 Daniel Baumann <daniel@debian.org>
#
# SPDX-License-Identifier: GPL-3.0+
#
# 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 3 of the License, or
# (at your option) any later version.
#
# 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.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.

set -e

if [ -z "${1}" ]
then

cat << EOF
Usage: ${0} ACCOUNT "KEY"

Examples:
  ${0} bad9 "ssh-ed25519 [...]"
  ${0} bad9 ssh-key.pub
  ${0} bad9 disabled
EOF

	exit 1
fi

PROGRAM="$(basename "${0}")"

BFH_USER="${1}"
BFH_KEY="${2}"

DATE="$(date +%Y-%m-%d\ %H:%M:%S)"
HOST="$(hostname -f 2> /dev/null || hostname)"

echo "${DATE} ${HOST} ${PROGRAM} ${*}" >> "/var/log/bfh-ssp/bfh-ssp-tools.log"
irk "irc://irc.oftc.net:6668/bfh-linux-sysadmin" "\x0300${PROGRAM}\x03@\x0312${HOST}:\x03 \x0303${BFH_USER}\x03"

Clean ()
{
	# shellcheck disable=SC2317
	rm -f "${_TMPFILE}"
}

trap 'Clean' EXIT HUP INT QUIT TERM

_TMPFILE="$(mktemp -t bfh-ssp_"${PROGRAM}".XXXXXXXX)"

cat > "${_TMPFILE}" << EOF
From: ${PROGRAM}+noreply@${HOST}
To: bfh-linux-ssp@lists.bfh.science
Subject: ${PROGRAM}: ${BFH_USER}

Date: ${DATE}
Command: ${PROGRAM} ${@}
EOF

# shellcheck disable=SC2002
cat "${_TMPFILE}" | /usr/sbin/sendmail -t

# Add or replace SSH key in LDAP
/usr/libexec/bfh/ssh-key --user "${BFH_USER}" --key "${BFH_KEY}" --quiet
