#!/bin/sh

alterator_api_version=1
HOSTNAMECTL=/usr/bin/hostnamectl
max_hostname_length=64
cachedir="/var/cache/alterator/hostname"

. alterator-sh-functions
. shell-config

### hostname
check_hostname()
{
	local hn="$1"
	local length=

	length=${#hn}
	if [ $length -gt $max_hostname_length ]; then
		write_error "`_ "Host name is too long"`"
		return 1
	fi
	return 0
}

read_computer_name()
{
	local netconfig="/etc/sysconfig/network"
	local hostname_file="/etc/hostname"
	local value=

	[ -f "$HOSTNAMECTL" ] && value="$($HOSTNAMECTL hostname --static)"

	if [ -z "$value" ]; then
		if [ -f "$hostname_file" ]; then
			value="$(cat "$hostname_file" | head -1)"
		elif [ -f "$netconfig" ]; then
			value="$(shell_config_get "$netconfig" HOSTNAME)"
		fi
	fi

	[ -n "$value" ] || value="localhost.localdomain"
	echo "$value"
}

write_computer_name()
{
	local netconfig="/etc/network"

	check_hostname "$1" || return

	if [ -f "$netconfig" ]; then
		shell_config_set "$netconfig" HOSTNAME "$1"
		shell_config_del "$netconfig" DOMAINNAME
	fi

	if [ -f "/etc/hostname" ]; then
		echo "$1" >"/etc/hostname"
	fi
}

on_message()
{
	case "$in_action" in
		read)
			write_string_param computer_name "$(read_computer_name)"
		;;
		write)
			[ -n "$in_computer_name" ] && write_computer_name "$in_computer_name"
		;;
	esac
}

message_loop
