#!/bin/sh

# Make sure umask is set to owner only
umask 0077

# find the current path to master executable
FINDNAME=$0 
while [ -h $FINDNAME ] ; do FINDNAME=`command -v awk > /dev/null && ls -ld $FINDNAME | awk '{print $NF}' || ls -ld $FINDNAME | rev | cut -d ' ' -f 1 | rev` ; done 
RUNDIR=`echo $FINDNAME | sed -e 's@/[^/]*$@@'` 
unset FINDNAME

# cd to top level agent home
if test -d $RUNDIR; then
  cd $RUNDIR/.. 
else
  cd ..
fi

#create log directory, in case it doesn't exist
_AGENTOPERATIONSLOGFOLDER=`pwd`/log
if ! test -d $_AGENTOPERATIONSLOGFOLDER ; then
      mkdir $_AGENTOPERATIONSLOGFOLDER
fi
_AGENTOPERATIONSLOGFILE=$_AGENTOPERATIONSLOGFOLDER/agent.operations.log

# Create header of execution log: 2 lines, command, date_time.
NAME=`basename "$0"`

echo "" >> $_AGENTOPERATIONSLOGFILE
echo "=================================================================================" >> $_AGENTOPERATIONSLOGFILE
echo "The outer script $NAME started successfully at $(date)" >> $_AGENTOPERATIONSLOGFILE
echo "Requested command: ${1} ">> $_AGENTOPERATIONSLOGFILE
echo "=================================================================================" >> $_AGENTOPERATIONSLOGFILE
# echo user for audit
ID_COMMAND=`id`
CURRENT_USER=`expr "$ID_COMMAND" : '.*(\(.*\)) gid='`
echo "currentUser="$CURRENT_USER >> $_AGENTOPERATIONSLOGFILE

ROLLBACK_PROPERTIES=conf/rollback.properties
PROP_NAME=set.HQ_AGENT_BUNDLE

# resolve the HQ Agent Bundle property
AGENT_BUNDLE=`command -v awk > /dev/null && grep $PROP_NAME $ROLLBACK_PROPERTIES | awk -F= '{print $2}' || grep $PROP_NAME $ROLLBACK_PROPERTIES | cut -d '=' -f 2`
echo "AGENT_BUNDLE = $AGENT_BUNDLE" >> $_AGENTOPERATIONSLOGFILE

if test -d "./bundles/$AGENT_BUNDLE"; then
  # be safe and set permissions for the invoked script
  echo "Setting permissions:" >> $_AGENTOPERATIONSLOGFILE
  echo "	1. chmod -R +x ./bundles/$AGENT_BUNDLE/bin/*" >> $_AGENTOPERATIONSLOGFILE 
  chmod -R +x ./bundles/$AGENT_BUNDLE/bin/* 2>&1 | tee -a $_AGENTOPERATIONSLOGFILE
  # Fix permissions issues on HPUX
  echo "	2. chmod -R +x ./bundles/$AGENT_BUNDLE/pdk/lib/*.sl" >> $_AGENTOPERATIONSLOGFILE
  chmod -R +x ./bundles/$AGENT_BUNDLE/pdk/lib/*.sl 2>&1 | tee -a $_AGENTOPERATIONSLOGFILE 
  #also for backround.sh which is in different folder
  echo "	3. chmod  +x ./bundles/$AGENT_BUNDLE/*" >> $_AGENTOPERATIONSLOGFILE
  chmod  +x ./bundles/$AGENT_BUNDLE/* 2>&1 | tee -a $_AGENTOPERATIONSLOGFILE
  # pass on the command to the bundle
  #echo "Invoking agent bundle $AGENT_BUNDLE"
  if [ "$1" = "set-property" ]; then
    echo "invoking script: ./bundles/$AGENT_BUNDLE/bin/hq-agent-nowrapper.sh $@" >> $_AGENTOPERATIONSLOGFILE
    ./bundles/$AGENT_BUNDLE/bin/hq-agent-nowrapper.sh "$@"
  else
    echo "invoking script: ./bundles/$AGENT_BUNDLE/bin/ep-agent.sh $@" >> $_AGENTOPERATIONSLOGFILE
    ./bundles/$AGENT_BUNDLE/bin/ep-agent.sh "$@"
  fi
else
  echo "Bundle $AGENT_BUNDLE does not exist!" | tee -a $_AGENTOPERATIONSLOGFILE 
fi
