#!/bin/ksh
#
# $Id: start_njmon_now,v 1.1 2023/03/27 19:59:17 root Exp root $
# 
# The following code is Confidential and is covered by the installation license
# (c) Copyright Fortra, LLC. and its group of companies.
# 
#&& starts njmon to run till the end of the day every 5 mins.
# 
#&@ pndcutils.sh is also required
# 
#& An attempt is made to start njmon every 15 minutes if it is not aleady running.
#&% This occurs via crontab at 1, 16, 31, 46 minutes after the hour
#&% In crontab, the -q (quiet) option is used.
# 
#
# Changes
##### add -c, -s, "-24" options
##### test "is_njmon_running" more
##### notify when creating .01 etc. files
##### option to not start when a current njmon is running (use with -f)
#	verify and expand is_njmon_running  tnm code
#
# Additional njmon options can be added by modifying the njmonopts variable in 
# the pn.config file (i.e. -t top data on each snap )
#       

# invocdir=`dirname $0`  # invocation dir (default for temp/data files, utilities) 
# changed for njmon # /usr/local/mpg/njmon_data
invocdir='/usr/local/mpg/njmon_data'  # invocation dir (default for temp/data files, utilities)
# changed for njmon
mkdir -p $invocdir
# gzip older json files except the most recent one.
ls -1tr ${invocdir}/*json | sed '$d' | xargs gzip

# Next line necessary to ensure application run correctly from cron.
# cd $invocdir

# Added a time reference file for 0000 today called mpg_today 
# for external data collection process of current data
jdate=`date +%Y%m%d`
touch -t ${jdate}0000 ${invocdir}/mpg_today
if [ ! -s  ${invocdir}/last_cend ]; then
   echo "start_njmon_now `date`" > ${invocdir}/last_cend
   touch -t ${jdate}0000 ${invocdir}/last_cend
fi

if [ "X${auto_start_njmon}" = "XF" ] ; then
   # Returning 0 even though not starting, because it is intentionally 
   # not started, by having the auto_start_njmon variable set to F
   if [ ! -z "$debug" ] ; then 
      echo "auto_start_njmon = (${auto_start_njmon})" 
   fi   
   exit 0  
fi

export datafile invocdir njmondatadir installdir mpgdatadir

# Next line can be use to check variables
# set > $invocdir/set_start_njmon_now.mpginc

let samplefreqmins=5
# ext_data_collect value is set in pn.config
# External data collection process options are set in pnedcp.config 

function usage {
   echo "USAGE: $0 <options>"
   echo "  where options may be any of:"
   echo "  -f #	force start (don't ask, just do it)"
   echo "     # will not restart an njmon running in the current dir, use kill first"
   echo "  -m #		sample frequency in whole minutes (default: $samplefreqmins)"
   echo "  -d njmondatadir	njmon data directory"
}

function get_start_njmon_now_command {
   phh=`date +%H`
   pmm=`date +%M`
   hh=${phh##0}
   mm=${pmm##0}
   let samplefreqsecs=$samplefreqmins*60
   let ssf=$hh*3600+$mm*60
   let spd=24*3600
   let rsecs=$spd-$ssf
   let nsamples=$rsecs/$samplefreqsecs
   # Only start njmon from mpg directory.
   # Version of njmon that are too old cause problems.
   export nmf
   # njmon_start_command="$invocdir/njmon -m $njmondatadir -F $nmf -s$samplefreqsecs -c$nsamples ${njmonopts}"
   # njmon builds a file for err and json and needs a directory specified.
   # Defaults to /usr/local/mpg/njmon_data if not specified.
   njmon_start_command="/usr/lbin/njmon -m $njmondatadir -f -s$samplefreqsecs -c$nsamples ${njmonopts}"
   echo $njmon_start_command
}

# if the default output file exists, try <file>.01 etc...
function get_available_njmon_outfile {
   typeset nmf=`date +mpg_%Y%m%d.njmon`
   export nmf=${njmondatadir}/$nmf
   if [ -e $nmf ] ; then
      nmft=$nmf
      nmfnum=0
      while [ -e $nmft ] ; do
         let nmfnum=$nmfnum+1
         let nmfext=$nmfnum
         if [ $nmfext -lt 10 ] && [ ${#nmfext} -lt 2 ] ; then nmfext="0$nmfext"; fi
         nmft=$nmf.$nmfext
      done
      export nmf=$nmft
   fi
   echo $nmf
}

function set_echo_opt {
   # set the bash xpg_echo shopt if unset (so echo \c works)
   # ksh works by default
   shell=`basename $SHELL`
   if [ "$shell" = "bash" ] ; then
      shopt xpg_echo > /dev/null 2>&1
      xpge=$?
      if [ "$xpge" = "1" ] ; then # bash, but unset
         shopt -s xpg_echo > /dev/null 2>&1
      fi
   fi
}

function is_njmon_running {
   basename_pwd=`basename $PWD`
   basename_njmondata=`basename $njmondatadir`
   cnm=`ps -efl | grep "\/njmon" | grep -v grep | grep $basename_njmondata`
   running=$?
   tnm=`ps -efl | egrep "\/usr\/lbin\/njmon" | grep -v grep | grep $basename_njmondata`
   thisrunning=$?
   # Need to fix test for running.
   set > /tmp/set_njmon_running
   if [ "$running" != "0" ] ; then
      cnm="none:"
   else
      if [ "$thisrunning" = "0" ] ; then
         cnm="THIS:$tnm"
      else
         cnm="OTHER:$cnm"
      fi
   fi

echo $cnm
}

while getopts "efvqm:d:" opt ; do
   case $opt in
	f)	force_start="T" ;;
	v)	verbose="T" ;;
	q)	quiet="T" ;;
	m)	opt_samplefreqminutes=$OPTARG ;;
	d)	opt_njmondatadir=$OPTARG ;;
	*)	usage;  exit ;;
   esac
done
shift `expr $OPTIND - 1`

if [ "X$njmondatadir" = "X" ] ; then
   njmondatadir=$invocdir
fi
if [ "X$opt_njmondatadir" != "X" ] ; then
   njmondatadir=$opt_njmondatadir ;
fi
if [ "X$opt_samplefreqminutes" != "X" ] ; then
   samplefreqmins=$opt_samplefreqminutes ;
fi
set_echo_opt
export nmf=`get_available_njmon_outfile`
nmc=`get_start_njmon_now_command`
running_njmons=`is_njmon_running`
which_njmons=${running_njmons%%:*}
running_njmons_str="${running_njmons}"

# Changed behaviour of start_njmon_now to always start the external data collector process 
# script to keep the mpgdata2_current.hostname file up to date
# Will export variable ext_data_collect to have collection scripts record or not record data.
# The snap script will always keep the current data updated.
#
# Performance Navigator External Data Collection Process
# NMON variables to start the collection process.
# Type of timestamp TIMESTAMP 0 is Tnumber, 1 is timedate
export TIMESTAMP=0
export pnedcp_out="${mpgdatadir}/mpgdata3.$sysname"
export pnedcp_day="${mpgdatadir}/mpgdata3_day.$sysname"
export pnedcp_day_last="${mpgdatadir}/mpgdata3_day_last.$sysname"
export pnedcp_ps="${mpgdatadir}/mpgdataps_${jdate}.$sysname"
export pnedcp_ps_current="${mpgdatadir}/mpgdata5_current.$sysname"
 # Added to allow copying mpg_*.njmon & mpg_*.njmon.## to 
 # mpgdata2_current.hostname
export pnedcp_current="${mpgdatadir}/mpgdata2_current.$sysname"
 # This script is ran to put headers in data.
export NMON_START="${installdir}/pnedcp_start.sh"
 # This script is ran gather snap data.
export NMON_SNAP="${installdir}/pnedcp_snap.sh"
 # This script is ran at the end of gathering data.
export NMON_END="${installdir}/pnedcp_end.sh"
 # Indicates how often external data is collected. 1 every time, 2 every other
unset NMON_ONE_IN 
 # export NMON_ONE_IN=1 
export TIMESTAMP NMON_START NMON_SNAP NMON_END NMON_ONE_IN pnedcp_out pnedcp_day pnedcp_current 
PATH=$PATH:/usr/local/mpg

if [ "$ext_data_collect" = "T" ] ; then
   export ext_data_collect="T"
else  # Any answer other than "on" is off 
   export ext_data_collect="F"
fi

if [ "$ext_ps_collect" = "T" ] ; then
   export ext_ps_collect="T"
else  # Any answer other than "on" is off 
   export ext_ps_collect="F"
fi

export=

if [ "$force_start" = "T" ] ; then
   runit="Y"
   fsmsg="starting njmon now with command:\n$nmc"
   if [ "$which_njmons" = "THIS" ] ; then
      if [ "$verbose" = "T" ] ; then
         echo "FOUND CURRENTLY RUNNING njmon PROCESS HERE, not starting another:"
         echo "(${running_njmons_str})"
      fi
      fsmsg=""
      runit="N"
   elif  [ "$which_njmons" = "OTHER" ] ; then 
      if [ "$verbose" = "T" ] ; then
         echo "found currently running njmon processes in other locations:"
         echo $running_njmons_str
      fi
   fi
   if [ "$quiet" != "T" ] && [ ! -z "$fsmsg" ] ; then echo $fsmsg ; fi
else
   if [ "$which_njmons" != "none" ] ; then
      echo "FOUND CURRENTLY RUNNING njmon PROCESSES:"
      echo "(${running_njmons_str})"
      snprompt="Are you sure you want to start njmon now? \c"
   else
      snprompt="do you want to start njmon now? \c"
   fi
   runit="N"
   echo "command to start njmon now is:"
   echo $nmc
   echo $snprompt
   read answer
   yn=${answer:-"n"}
   if [ "$yn" = "Y" ] ; then runit="Y" ; fi
   if [ "$yn" = "y" ] ; then runit="Y" ; fi
fi
# echo "answer=$answer, yn=$yn, runit=$runit"
# echo '$TIMESTAMP  $NMON_START  $NMON_SNAP  $NMON_END  $NMON_ONE_IN'
# echo "$TIMESTAMP  $NMON_START  $NMON_SNAP  $NMON_END  $NMON_ONE_IN"

if [ "$runit" = "Y" ] ; then
   # echo "Running:   $nmc"
   $nmc
fi
