#!/usr/local/bin/bash
#
# Copyright (c) 2016 Joyent Inc., All rights reserved.
#
# This script sets the password for the root user if this:
#
#  "users": [{"name": "root"}] 
#
# has been set in the image manifest.
#
# This script must only be run once via firstboot. The script will first check 
# /etc/master.passwd to ensure a root password is not being overwritten.

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

# Check /etc/master.passwd. If root pass is set, exit so we don't clobber an 
# already set password.
passset=$(cat /etc/master.passwd | grep Charlie | awk -F':' '{print $2;}')
if [[ -n $passset ]]; then
  lib_triton_fatal "The root password already set in /etc/master.passwd. Exiting."
fi

# Check if root_pw is set in meta data
pass=$($MDATA_GET root_pw)
if [[ $? -eq 0 ]] ; then
    lib_triton_info "Setting root password to value of meta-data root_pw."
    echo "${pass}" | pw usermod root -h 0
else
    lib_triton_info "No root password set in root_pw. Skipping."
fi

exit 0
