#!/system/bin/sh

HOSTS_FILE="/system/etc/hosts"
IP="127.0.1.1"

hname="localhost"
hname_prefix="tp-"
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}"
full_hostname="$(echo "${full_hostname}" | tr -d '\n\t ')"
if [ "${full_hostname}"x = ""x ] ; then
	echo "unable to get hostname"
	log -p e "/vendor/at-boot.d/001-set-hostname: unable to get hostname"
	exit 0
fi

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

hostname "${full_hostname}"
echo -e "${hosts}" > ${HOSTS_FILE}
log "/vendor/at-boot.d/001-set-hostname: set hostname to ${full_hostname}"

exit 0
