#!/bin/bash
PATH=/opt/local/bin:/opt/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin
export PATH

set -o errexit
set -o xtrace

# Set basedir and default config file
BASE=$(dirname $0)
ZONECONFIG=/root/zoneconfig

# This script should only continue if
#
#  1) executed as a SMF start method; and
#  2) /var/svc/provisioning exist.
#
# Otherwise, pretend success but do nothing
#
# Pre-create /var/svc/provisioning if /root/zoneconfig exists
# to stay backwards compatible.

[ -e ${ZONECONFIG} ] && touch /var/svc/provisioning
[ "${SMF_METHOD}" == "start" ] && [ -e /var/svc/provisioning ] || exit 0

function log {
  local WHERE=$(basename ${INC-zoneinit})
  echo "${WHERE}: $1"
}

function exit_handler {
  local WHERE=$(basename ${INC-zoneinit})
  local EXITCODE=${2:-95}

  if [ ${EXITCODE} -gt 0 ]; then
    echo "${WHERE}: $1 ${EXITCODE}"

    # Renaming 'provisioning' to 'provision_failure' tells the provisioner
    # that we failed and the machine is no good

    [ -e /var/svc/provisioning ] && mv /var/svc/provision{ing,_failure}

    # Status 95 tells the SMF restarter to fail fatally (not try again)
    exit 95
  fi
}

trap 'exit_handler "received exit status" $?' EXIT

START_TIME=$(date +%s)
log "(start)"

# Pull in and execute all operations from the 'includes' directory
for INC in ${BASE}/includes/*.sh
do
  log "(start)"
  source ${INC}
done
unset INC

END_TIME=$(date +%s)
RUN_TIME=$((END_TIME-START_TIME))
if [ ${RUN_TIME} -gt 0 ]; then
  log "total runtime ${RUN_TIME} seconds"
fi

# provisioner takes over
log "(finish)"
exit 0
