#!/usr/bin/bash
#
# Set the hostname of a VM.
# Copyright (c) 2016 Joyent Inc., All rights reserved.

set -o errexit
set -o pipefail

usage() {
cat << EOF >&2

Usage: $0 HOSTNAME

EOF
exit 2;
}

[[ ! $1 ]] && usage;

export LANG=C
PATH="/opt/local/bin:/opt/local/gnu/bin:/opt/local/sbin:/usr/bin:/usr/sbin";
vm_host="$1";
vm_uuid=$(zonename);
hosts_file='/etc/inet/hosts';
ip_external=$(mdata-get sdc:nics | /usr/bin/json -ag ip -c 'this.nic_tag === "external"' 2>/dev/null);
ip_internal=$(mdata-get sdc:nics | /usr/bin/json -ag ip -c 'this.nic_tag === "internal"' 2>/dev/null);

echo "* Setting hostname for ${vm_uuid}..";

cat > ${hosts_file} << EOF
::1             localhost
127.0.0.1       localhost loghost
EOF

if [[ -n ${ip_external} ]]; then
    printf '%s\t%s\n' "${ip_external///*}" "${vm_host}" >> "${hosts_file}"
fi
if [[ -n ${ip_internal} ]]; then
    printf '%s\t%s\tloghost\n' "${ip_internal///*}" "${vm_uuid}" >> "${hosts_file}"
fi

echo "${vm_host}" > /etc/nodename

hostname ${vm_host}

echo "* Changed hostname to ${vm_host}.  You will need to reboot.";
