#!/bin/sh
# Deterministically set system hostname from /etc/hostname.d/
#
# Highest numbered file wins (lexicographic sort, 90-dhcp > 50-configured > 10-default)
#
# Priority scheme:
#   10-default       - Bootstrap/factory default (%h-%m format)
#   50-configured    - From confd /system/hostname
#   90-dhcp-<iface>  - From DHCP clietn on interface (highest priority)

HOSTNAME_D="/etc/hostname.d"

# Find highest priority file (reverse lexicographic)
set -- "$HOSTNAME_D"/*
if [ ! -e "$1" ]; then
    logger -it confd "No hostname sources found in $HOSTNAME_D"
    exit 1
fi

file=$(printf '%s\n' "$@" | sort -r | head -n1)
IFS= read -r new < "$file"
new=$(printf '%s' "$new" | tr -d '\r\n\t ')
if [ -z "$new" ]; then
    logger -it confd "Empty hostname in $file"
    exit 1
fi

if [ ${#new} -gt 64 ]; then
    logger -it confd "Hostname too long (${#new} > 64) in $file"
    exit 1
fi

# Check if hostname has actually changed
if [ "$new" = "$(hostname)" ]; then
    # No change needed, exit silently
    exit 0
fi

# Set the hostname
if hostname "$new"; then
    echo "$new" > /etc/hostname
fi

# Update /etc/hosts (127.0.1.1 entry for proper name resolution)
if grep -q "^127\.0\.1\.1" /etc/hosts; then
    sed -i -E "s/^(127\.0\.1\.1\s+).*/\1$new/" /etc/hosts
else
    # Add entry if it doesn't exist
    echo "127.0.1.1	$new" >> /etc/hosts
fi

# Notify services of hostname change, skip while in bootstrap
initctl -nbq touch sysklogd
if ! runlevel >/dev/null 2>&1; then
    exit 0
fi

initctl -bq status lldpd && lldpcli configure system hostname "$new_hostname" 2>/dev/null
initctl -bq touch mdns-alias 2>/dev/null

# If called from dhcp script we need to reload to activate new name in syslogd
# Otherwise we're called from confd, which does the reload when all is done.
if [ -n "$1" ]; then
    initctl -b reload
fi

exit 0
