#!/bin/bash
# Set or show this machine's pretty hostname, PRETTY_HOSTNAME in
# /etc/machine-info. hostnamectl is systemd's writer; Slackware has neither,
# and the GRUB theme reads the name for its panel title.
# Copyright (C) 2026 Danilo M. <danix@danix.xyz>
# Licensed under the GNU General Public License v2 only.
#
#   udt-machine-name                  print the current name
#   sudo udt-machine-name "My Box"    set it
set -euo pipefail

file="${UDT_MACHINE_INFO:-/etc/machine-info}"

if [ $# -eq 0 ]; then
    [ -f "$file" ] && sed -n 's/^PRETTY_HOSTNAME=//p' "$file"
    exit 0
fi
if [ $# -ne 1 ] || [ -z "$1" ]; then
    echo "usage: $(basename "$0") [NAME]" >&2
    exit 2
fi
case "$1" in
    *[[:cntrl:]]*) echo "name must not contain control characters" >&2; exit 2 ;;
esac

# Double-quoted, with only \ and " escaped: the escapes both systemd's reader
# and the GRUB build's shlex understand the same way.
value="$1"
value="${value//\\/\\\\}"
value="${value//\"/\\\"}"
line="PRETTY_HOSTNAME=\"$value\""

# Every other key in the file (ICON_NAME, CHASSIS, ...) is kept as it was.
tmp="$(mktemp "$file.XXXXXX")"
trap 'rm -f "$tmp"' EXIT
{ [ -f "$file" ] && grep -v '^PRETTY_HOSTNAME=' "$file" || true; echo "$line"; } > "$tmp"
chmod 644 "$tmp"
mv "$tmp" "$file"
trap - EXIT
echo "$line"
