#!/usr/bin/env bash

# Script for RBA to run immediately after rack password change
#
# Author:     BK Box <bk.box@rackspace.com>
# Maintainer: BK Box <bk.box@rackspace.com>

if [[ -z ${SSH_CLIENT} && -n ${SUDO_USER} && "${USER}" == "root" ]]; then
  SSH_PID=$(ps --no-headers -p $(ps --no-headers -p $(ps --no-headers -p $PPID -o ppid) -o ppid) -o ppid)
  prompt="RBA END DATA:\nRBAPROMPT$"
else
  SSH_PID=$(ps --no-headers -p $PPID -o ppid)
  prompt="RBA END DATA:\nRBAPROMPT#"
fi

# Kill RBA SSH process upon exit to avoid hanging (RBA bug)
trap "echo -e ${prompt}; sleep 2; kill -9 $SSH_PID 2>/dev/null; exit $?" EXIT

exists() {
  if command -v $1 &>/dev/null
  then
    return 0
  else
    return 1
  fi
}

URL="http://c1952.r52.cf2.rackcdn.com"
SCRIPT="mgc.sh"
RBA_START="RBA START STATUS:"
RBA_END="RBA END STATUS:"

##
# Grab the remote script for execution
if exists wget; then
  bash <(wget ${URL}/${SCRIPT} --timeout=60 --tries=10 -q -O -) --rba "$@"
elif exists curl; then
  bash <(curl --ipv4 --retry 10 -s -L ${URL}/${SCRIPT}) --rba "$@"
fi
E_SCRIPT_STATUS=$?
exit $E_SCRIPT_STATUS
