#!/bin/bash
#***** LAVA Config Copyright 2026 LAVA Controls - Stephen Loeckle *****
# lava-mailfrom - put the box name in the sender of the unattended-upgrades report
#
# unattended-upgrades sends its report from plain "root", so every box looks the same in a
# mailbox and the box name is only at the end of a long subject. apt configuration cannot
# expand the hostname by itself, so this writes it into a generated file:
#   /etc/apt/apt.conf.d/53unattended-upgrades-sender
#     Unattended-Upgrade::Sender "BOXNAME <BOXNAME@lavacontrols.com>";
# Run by the lavaconfig postinst and by lavasetup --name (box rename).

HOSTNAMEFILE="${LAVA_MAILFROM_HOSTNAMEFILE:-/etc/hostname}"
OUT="${LAVA_MAILFROM_OUT:-/etc/apt/apt.conf.d/53unattended-upgrades-sender}"
DOMAIN="lavacontrols.com"

# /etc/hostname first: after a rename it already holds the new name before the reboot.
name=""
if [ -s "$HOSTNAMEFILE" ]; then
    name=$(head -n 1 "$HOSTNAMEFILE")
fi
if [ -z "$name" ]; then
    name=$(hostname 2>/dev/null)
fi
name=${name%%.*}
name=$(printf '%s' "$name" | tr -cd 'A-Za-z0-9-')

if [ -z "$name" ] || [ "$name" = "localhost" ]; then
    echo "lava-mailfrom: no usable box name, leaving the default sender" >&2
    rm -f "$OUT"
    exit 0
fi

tmp="$OUT.tmp.$$"
{
    echo "// Generated by lavaconfig (lava-mailfrom). Do not edit, it is rewritten on upgrade and rename."
    echo "Unattended-Upgrade::Sender \"$name <$name@$DOMAIN>\";"
} > "$tmp" || exit 1
chown root:root "$tmp" 2>/dev/null
chmod 644 "$tmp"
mv -f "$tmp" "$OUT"
echo "   unattended-upgrades reports are sent as $name <$name@$DOMAIN>"
