#!/usr/bin/env bash
# system/hostname -- change the machine name safely
#
# Changing the hostname also updates /etc/hosts, otherwise sudo and some
# services start complaining about an unresolvable host.
set -o pipefail
SELF=$(readlink -f "${BASH_SOURCE[0]}")
NV_BASE=$(cd "$(dirname "$SELF")/../../.." && pwd)
export NV_BASE
# shellcheck source=/dev/null
. "$NV_BASE/lib/core/bootstrap.sh"

nv_require_root || exit 1
ui_header "$(t sys_m_hostname)"

ui_kv "$(t hname_now)" "$(hostname 2>/dev/null)"
ui_kv "$(t hname_fqdn)" "$(hostname -f 2>/dev/null || echo -)"
ui_blank
ui_info "$(t hname_hint)"
ui_blank

printf '  %s: ' "$(t hname_prompt)"
read -r name || exit 130
name=$(nv_lower "$(nv_trim "$name")")
case $name in
    '') exit 0 ;;
    *[!a-z0-9.-]*) ui_err "$(t hname_bad)"; exit 2 ;;
esac
[ ${#name} -le 63 ] || { ui_err "$(t hname_bad)"; exit 2; }

ui_warn "$(t hname_warn)"
ui_confirm "$(t hname_confirm "$name")" n || exit 0

nv_backup_path /etc/hostname hostname >/dev/null 2>&1 || true
nv_backup_path /etc/hosts hostname >/dev/null 2>&1 || true

if nv_have hostnamectl; then
    hostnamectl set-hostname "$name" || { nv_fail 6111 "$(t hname_failed)"; exit 1; }
else
    printf '%s\n' "$name" >/etc/hostname
    hostname "$name" 2>/dev/null || true
fi

ip=$(nv_primary_ip)
if [ -n "$ip" ] && ! grep -qE "[[:space:]]$name(\$|[[:space:]])" /etc/hosts; then
    printf '%s %s\n' "$ip" "$name" >>/etc/hosts
fi
nv_trace hostname "$name"
ui_ok "$(t hname_done "$name")"
ui_info "$(t hname_note)"
exit 0
