#!/bin/bash
#
# Copyright 2015-2016 VMware, Inc.  All rights reserved.
#
# vcha-vc-support     Gather support bundle from the specified vCenter HA node.
#

usage ()
{
     echo "Usage: vcha-vc-support <peer|witness>"
     echo "Default: Collects bundles under /storage/log/ and streams to stdout"
     exit
}

while getopts h arg ; do
   case "$arg" in
      "h") usage ;;
        *) usage ;;
   esac
done

NODE_TYPE=$1

if [ "$NODE_TYPE" != "peer" ] && [ "$NODE_TYPE" != "witness" ]; then
   usage
   exit 1
fi

VCHA_CFG_PATH="/etc/vmware-vcha/vcha.cfg"
XML_CFG_BIN_PATH="/usr/lib/vmware-vpx/py/xmlcfg.py"
VCHA_GATHER_PY_SCRIPT="/usr/lib/vmware-vcha/scripts/gather_support_bundle.py"

if [ ! -f $VCHA_CFG_PATH ]; then
   exit 1
fi

self_ip=`$XML_CFG_BIN_PATH -f $VCHA_CFG_PATH get /config/vcha/node/name`
witness_ip=`$XML_CFG_BIN_PATH -f $VCHA_CFG_PATH get /config/vcha/clusterConfig/witness/ip`

if [ "$self_ip" == "$witness_ip" ]; then
   # Nothing to do since we are running vc-support on the Witness node.
   exit 1
fi

target_ip=""
if [ "$NODE_TYPE" == "witness" ]; then
   target_ip=$witness_ip
else
   node1_ip=`$XML_CFG_BIN_PATH -f $VCHA_CFG_PATH get /config/vcha/clusterConfig/peer/node1/ip`
   node2_ip=`$XML_CFG_BIN_PATH -f $VCHA_CFG_PATH get /config/vcha/clusterConfig/peer/node2/ip`
   if [ "$self_ip" == "$node1_ip" ]; then
      target_ip="$node2_ip"
   else
      target_ip="$node1_ip"
   fi
fi

tmp_dir="/storage/core/"
cur_time=$(date "+%m-%d-%Y-%H-%M-%S")
tmp_filename="vcha-$target_ip-vc-support-$cur_time.tgz"

${VMWARE_PYTHON_BIN} $VCHA_GATHER_PY_SCRIPT -d $tmp_dir -f $tmp_filename -p $target_ip

ret_code=$?

if [ $ret_code == 0 ]; then
    cat $tmp_dir$tmp_filename 2>/dev/null
    rm -f $tmp_dir$tmp_filename
else
    exit 1
fi

