#!/bin/bash

# this is executed on each boot, except the first,
# before entering the first runlevel.

COMMONUTILS=/usr/sbin/vpxd_commonutils

. $COMMONUTILS

VPXD_SERVICECFG=/usr/sbin/vpxd_servicecfg

LN=/bin/ln
LS=/bin/ls
RM=/bin/rm
RMDIR=/bin/rmdir
CUT=/usr/bin/cut
GREP=/usr/bin/grep
#
# remove all subdirs of /storage that have some pattern in their
# name and allow exceptions.
#
cleanup_storage()
{
   local MASTER_PATTERN=$1
   local EXCLUDE=$2

   if [ -z "$MASTER_PATTERN" ] || [ -z "$EXCLUDE" ]; then
      return 1
   fi

   $LS /storage | $GREP "$MASTER_PATTERN" | $GREP -v "$EXCLUDE" |
   while read dirname
   do
      $RMDIR "/storage/$dirname"
   done

   return 0
}

#
# fix the log and core directory symlinks, if needed.
#
setup_symlinks()
{
   local GUID=$(read_instanceUuid)
   if [ -z "$GUID" ]; then
      # revert to local, shouldn't happen.
      $LN -sf -T /storage/log/vmware /var/log/vmware
      $LN -sf -T /storage/log/remote /var/log/remote
      $LN -sf -T /storage/core /var/core
      return 1
   fi

   local LOG_MOUNTPOINT=`$VPXD_SERVICECFG -q storage read log | $GREP VC_STORAGE_MOUNTPOINT | $CUT -f 2 -d =`
   if [ -n "$LOG_MOUNTPOINT" ]; then
      # use the nfs share
      $LN -sf -T "$LOG_MOUNTPOINT/$GUID/log/vmware" /var/log/vmware
      $LN -sf -T "$LOG_MOUNTPOINT/$GUID/log/remote" /var/log/remote

      # delete other nfs log mountpoints
      cleanup_storage "nfs.log." "`basename $LOG_MOUNTPOINT`"
   else
      # use the local directory
      $LN -sf -T /storage/log/vmware /var/log/vmware
      $LN -sf -T /storage/log/remote /var/log/remote

      # delete other nfs log mountpoints
      cleanup_storage "nfs.log." "dummy"
   fi

   local CORE_MOUNTPOINT=`$VPXD_SERVICECFG -q storage read core | $GREP VC_STORAGE_MOUNTPOINT | $CUT -f 2 -d =`
   if [ -n "$CORE_MOUNTPOINT" ]; then
      # use the nfs share
      $LN -sf -T "$CORE_MOUNTPOINT/$GUID/core" /var/core

      # delete other nfs core mountpoints
      cleanup_storage "nfs.core." "`basename $CORE_MOUNTPOINT`"
   else
      # use the local directory
      $LN -sf -T /storage/core /var/core

      # delete other nfs core mountpoints
      cleanup_storage "nfs.core." "dummy"
   fi

   return 0
}

setup_symlinks

# update embedded DB parameters
set_emb_db_params

#
# grow the local storage partitions onto new enlarged disks.
#
$VPXD_SERVICECFG storage lvm autogrow
# Recreate swap since swap disk could have been changed
$VPXD_SERVICECFG storage lvm recreate_swap

# execute the runonce scripts
run_once


