#!/usr/local/bin/bash
#
# Copyright (c) 2016 Joyent Inc., All rights reserved.
# Set the hostname of the VM if it's not already configured by the user.

# load common functions and vars
. /usr/local/lib/smartdc/common.lib

grep hostname= /etc/rc.conf &>/dev/null
if [[ $? -ne 0 ]]; then
  lib_triton_info "No hostname set in /etc/rc.conf."
  hostname=$($MDATA_GET sdc:hostname) && \
    lib_triton_info "Setting hostname to sdc:hostname: $hostname."
  
  if [[ $? -ne 0 ]]; then
    lib_triton_info "No value set for sdc:hostname."
    hostname=$($MDATA_GET sdc:uuid) && \
      lib_triton_info "Setting hostname to sdc:uuid: $hostname"
    
    if [[ $? -ne 0 ]]; then
      lib_triton_info "No value set for sdc:uuid. Setting empty hostname."
      hostname=""
      
    fi
  fi

  if [[ ! -z "$hostname" ]]; then
    lib_triton_info "Restarting /etc/rc.d/hostname"
    echo hostname="\"$hostname\" # Added by triton. This can be modified." >> /etc/rc.conf
    /etc/rc.d/hostname restart
  fi
fi

exit 0
