#!/bin/bash

###
# vCenter Server Appliance 6.0 Inventory Service Reset
##

echo '**********************************************************'
echo 'Copyright 2016 VMware, Inc.  All rights reserved'
echo '**********************************************************​'

g_abort () {
  # Graceful Abort.
  echo -ne "ABORTING! "
  echo $1
  echo -ne "Aborting is strongly encouraged. Do you want to continue regardless? (y/N) "
  while true; do
          read -p "" YN
          case $YN in
                  [Yy]*) break;;
                  [Nn]*) exit 1;;
                  *) exit;;
          esac
  done
}

f_abort () {
  # Forceful Abort.
  echo -ne "FORCEFULLY ABORTING! "
  echo $1
  exit 1
}

msg_header () {
  echo ""
  echo "###"
  echo "# $1"
  echo "##"
  echo ""
}

msg_header "Resetting Inventory Service Database"

echo "┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓"
echo "┃      ╱╲                                                                     ┃"
echo "┃     ╱  ╲     You should only ever use this if you cannot use:               ┃"
echo "┃    ╱    ╲    http://kb.vmware.com/kb/2113435                                ┃"
echo "┃   ╱      ╲   Always take a snapshot before running this script!             ┃"
echo "┃  ╱        ╲  You will lose Storage Profiles if you execute this script!     ┃"
echo "┃ ╱ WARNING! ╲                                                                ┃"
echo "┃ ────────────                                                                ┃"
echo "┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛"

echo -ne "Are you sure you want to continue ? (y/N) "
while true; do
        read -p "" YN
        case $YN in
                [Yy]*) break;;
                [Nn]*) exit;;
                *) exit;;
        esac
done

###
# Setting up environment variables
##

for x in /usr/lib/vmware-invsvc/lib/*.jar; do
  CP="${CP}:$x";
done;
PATH_ROOT=/usr/lib/vmware-invsvc

TOOL_CLASSPATH=""
TOOL_DIR=/usr/lib/vmware-vpx/inventoryservice-registration

for JAR in "${TOOL_DIR}"/*.jar; do
  if [ -f "${JAR}" ]; then
    TOOL_CLASSPATH="${TOOL_CLASSPATH}:${JAR}"
  fi
done

TOOL_CLASSPATH="${TOOL_CLASSPATH}:${TOOL_DIR}"

###
# Getting data for Inventory Service config files
##

isinst=`grep -oP '\Q<instanceUuid>\E.*\Q</instanceUuid>\E' /usr/lib/vmware-vpx/endpoints/qs-endpoint.xml | sed -r 's_.*>(.*)<.*_\1_g'`
ispw=`grep 'dataservice.xdb.password' /usr/lib/vmware-invsvc/lib/server/config/dataservice.properties | sed -r 's_dataservice.xdb.password=__g' | sed -r 's_[^a-zA-Z0-9]__g' `
iscmurl=`grep dataservice.cm.url /usr/lib/vmware-invsvc/lib/server/config/dataservice.properties | sed -r 's_dataservice.cm.url=__g'`


msg_header "Step 1: Stopping services: vSphere Web Client, Inventory Service, vCenter Server Service."

service vsphere-client stop || g_abort "Could not stop WebClient."
sleep 5
service vmware-invsvc stop
sleep 5
service vmware-vpxd stop || g_abort "Could not stop vCenter Server Service."


msg_header "Step 2: Deleting old Inventory Service Database."

rm -rf /storage/invsvc/xdb || g_abort "Could not delete directory: /storage/invsvc/xdb"

msg_header "Step 3: Preparing the new dataservice.properties file."

echo "Inventory Service Instance UUID: ${isinst}"
echo "Inventory Service Simplified Password: ${ispw}"

grep -v 'dataservice.xdb.password' /usr/lib/vmware-invsvc/lib/server/config/dataservice.properties >> /tmp/isdsprops
echo "dataservice.xdb.password=${ispw}" >> /tmp/isdsprops
echo "dataservice.instanceUuid=${isinst}" >> /tmp/isdsprops

cp /usr/lib/vmware-invsvc/lib/server/config/dataservice.properties /tmp/dataservice.properties.bak
cp /tmp/isdsprops /usr/lib/vmware-invsvc/lib/server/config/dataservice.properties || g_abort "Could not write new dataservice.properties file."

msg_header "Step 4: Creating a new Inventory Service Database"

java -classpath ${CP} -Dds.dbdir="/storage/invsvc/data/xdb" \
                      -Dvim.logdir="/var/log/vmware/invsvc" \
                      -Dds.servicecfg="${PATH_ROOT}/lib/server/config/dataservice.properties" \
                      -Dis_upgrade_uuid="${isinst}" \
     com.vmware.vim.dataservices.CreateDb \
        /storage/invsvc/xdb \
        /storage/invsvc/xdb/xdblog \
        default \
        default \
        "${ispw}" \
        4096 || g_abort "Could not create empty Inventory Service database."

msg_header "Step 5: Getting the current vCenter Server Solution User Certificates"

mkdir -p /tmp/ssl || g_abort "Could not create temporary ssl folder."
/usr/lib/vmware-vmafd/bin/vecs-cli entry getkey --store vpxd --alias vpxd --output /tmp/ssl/rui.key || f_abort "Could not fetch vCenter Server Solution User private key."
/usr/lib/vmware-vmafd/bin/vecs-cli entry getcert --store vpxd --alias vpxd --output /tmp/ssl/rui.crt || f_abort "Could not fetch vCenter Server Solution User certificate."

echo "Done."

msg_header "Step 6: Starting Inventory Service"

service vmware-invsvc start || f_abort "Inventory Service failed to start. Check /var/log/vmware/invsvc/inv-svc.log"
sleep 3

msg_header "Step 7: Starting vCenter Server Service"


service vmware-vpxd start || f_abort "vCenter Server Service failed to start. Check /var/log/vmware/vpxd/vpxd.log"

msg_header "Step 8: Re-registering vCenter Server Service to Inventory Service."

mkdir -p /tmp/vcreglogs
/usr/java/jre-vmware/bin/java -classpath "${TOOL_CLASSPATH}" -Dvim.logdir="/tmp/vcreglogs" com.vmware.vim.dataservices.vcregtool.RegisterVC  \
                              -action register \
                              -cmurl  "${iscmurl}" \
                              -vcfeedurl 'http://localhost:8095' \
                              -vccert /tmp/ssl/rui.crt \
                              -vcprivkey /tmp/ssl/rui.key \
                              -vcinstancecfg /etc/vmware-vpx/instance.cfg \
                              -vcendpointsdir /usr/lib/vmware-vpx/endpoints \
                              -vcextensionsdir /etc/vmware-vpx/extensions \
                              -vcforceregister true || f_abort "Registration failed."

sleep 5

msg_header "Step 9: Restarting all services."

service-control --stop
service-control --start

msg_header "Done. Wait for vSphere WebClient to start to confirm normal operation."
