#!/bin/bash -eu

. install2-init-functions
po_domain=alterator-kopidel
in_language="${in_language:-}"
. alterator-sh-functions

scripts_dir="${KOPIDEL_INSTALLER_ROOT-}/tmp/metadata/install-scripts"
if [[ -f "$scripts_dir/hostname-value" ]]; then
	IFS= read -r name < "$scripts_dir/hostname-value"
else
	. "$scripts_dir/hostname"
	IFS= read -r template < "$scripts_dir/hostname-template"
	name="$(render_target_hostname "$template" "${KOPIDEL_INSTALLER_ROOT-}/sys/class/net")"
fi

umask 022
exec_chroot /usr/lib/alterator/backend3/hostname <<-EOF
	_message:begin
	action:write
	computer_name:$name
	_message:end
EOF

if ! exec_chroot env -C /etc sh -ec '
	if [ -f sysconfig/network ]; then
		. shell-config
		stored=$(shell_config_get sysconfig/network HOSTNAME)
		if [ "$stored" != "$1" ] || grep -Eq "^[[:space:]]*DOMAINNAME=" sysconfig/network; then
			exit 1
		fi
	fi
	[ "$(cat hostname)" = "$1" ]
' sh "$name"; then
	echo "Could not persist the computer name $name in the target system." >&2
	exit 1
fi
