#!/system/bin/sh

HOSTS_FILE="/system/etc/hosts"
HOSTNAME_FILE="/drd-data/hostname"
IP="127.0.1.1"
hname_prefix="knxiq-"

# Set or remove the persistent hostname file
if [ "$1" = "--reset" ] ; then
	rm -f "$HOSTNAME_FILE"
elif [ "$1" != "" ] ; then
	echo "$1" > "$HOSTNAME_FILE"
fi

if [ -f "$HOSTNAME_FILE" ] ; then
	# use the persistent hostname file, if it was set from the GUI
	full_hostname="$(cat $HOSTNAME_FILE)"
else
	# build the hostname from ConfigServer properties
	hname="localhost"

	product_code="$(cat /vendor/staticconfig/device/config.json | jq -r '.product_code')"
	if [ -n "${product_code}" ] ; then
		hname_prefix="${product_code}-"
	fi

	if [ -f /drd-conf/hostname.prefix ] ; then
		hname_prefix="$(cat /drd-conf/hostname.prefix | tr -d '\n')"
	fi

	if [ -f /drd-conf/serial ] ; then
		hname="$(cat /drd-conf/serial | tr -d '\n')"
	fi

	full_hostname="${hname_prefix}${hname}"
fi

full_hostname="$(echo "${full_hostname}" | tr -d '\n\t ')"
if [ "${full_hostname}"x = ""x ] ; then
	echo "unable to get hostname"
	log -p e "drd-set-hostname: unable to get hostname"
	exit 0
fi

length="$(echo -n "${full_hostname}" | wc -c)"
if [ $length -gt 31 ] ; then
	full_hostname="$(echo -n "${full_hostname}" | sed "s/^${hname_prefix}//")"
fi
length="$(echo -n "${full_hostname}" | wc -c)"
if [ $length -gt 31 ] ; then
	full_hostname="$(echo -n "${full_hostname}" | cut -c -31)"
fi

hosts="$(cat ${HOSTS_FILE} | grep -v "^${IP}")"
hosts="${hosts}\n${IP}\t${full_hostname}"

hostname "${full_hostname}"
setprop net.hostname "$(hostname)"
setprop devinfo.name "$(hostname)"
echo -e "${hosts}" > ${HOSTS_FILE}
log "drd-set-hostname: set hostname to ${full_hostname}"

exit 0

