#!/pkg/bin/ksh
# ---------------------------------------------------------------------
# imdr_abort_debug_base_script 
#
# Aug 2011, SAIDARAO Y 
#
# Copyright (c) 2011-2012 by cisco Systems, Inc.
# All rights reserved.
#--------------------------------------------------------------------

# WARNING
# *******
# This script has limited time to complete its task.
# So think before adding new commands to this script, make sure that
# most important command are at the begining so they can get the chance
# to get collected.

# Need to run the script at prio 10
setprio 10

# Supported arguments that caller can pass
# ========================================
# $1: name of the process calling this script
# $2: filesystem to create the debug file

# Make sure caller provide the right number of arguments. Note that for
# testing purpose we allow no argument being passed, otherwise all the
# supported arguments has to be provided.
if [ "$#" -ne 0 -a "$#" -ne 2 ]; then
    echo "ERROR: Wrong number of arguments ($#)" >> /tmp/${proc}_imdr_abort_script_log
    echo "Usage: $0 [<proc_name> <media> " >> /tmp/${proc}_imdr_abort_script_log
    return 1
fi

# Try to find out the required arguments by ourself if is not provided
if [ "$#" -eq 0 ]; then
    # Get the info about who is calling us, i2c_server or envmon process
    pidin -p imdr -f a | grep -v pid > /dev/null
    if [ $? -eq 0 ]; then
        proc=imdr
    else
        proc=unknown
    fi

    # Get media to use for creating the debug file
    medium=/net/node0_RP0_CPU0/harddisk:
else
    proc=$1
    medium=$2
fi

node_name=`uname -n`

dest_fs="/net"

# Define the destination directory to copy the debug files
dest_dir=$medium"/imdr_debugs/"$node_name

logger "The destination directory is '$dest_dir'"

fs_ready=no

# Definition of maximum wait count and sleep time per wait count for
# the destination filesystem to be ready.
# The current definition allow us to wait for at least 1.5 minutes before
# giving up. This is more than enough time for the filesystem to be ready.
MAX_FS_READY_WAIT_CNT=18
SLEEP_TIME_PER_WAIT_CNT=5
(( total_wait_time = $SLEEP_TIME_PER_WAIT_CNT * $MAX_FS_READY_WAIT_CNT ))

# Function to make sure that the destination filesystem is accessible.
# If not, then we will check every SLEEP_TIME_PER_WAIT_CNT number of seconds
# for at least the amount of time defined in MAX_FS_READY_WAIT_CNT variable.
# This check is mainly used for SP nodes, where RP filesystem mount point
# might not be ready when we get executed by sysmgr.
check_dest_fs_ready()
{
    i=0
    while [ ! -e "$dest_fs" ]
    do
        (( i = i + 1 ))
        if [ "$i" -ge "$MAX_FS_READY_WAIT_CNT" ]; then
            logger "The '$dest_fs' filesystem is still not accessible after $total_wait_time seconds, aborting execution of $0 script"
            return 1
        fi
        sleep $SLEEP_TIME_PER_WAIT_CNT
    done
    return 0
}

# First check if destination filesystem is ready
if [ "$fs_ready" = "no" ]; then
    check_dest_fs_ready
    if [ "$?" -ne "0" ]; then
        return 1
    fi
    fs_ready=yes

#check if storage medium is available, if not return failure
    ls  $medium 1>/dev/null 2>/dev/null
    if [ "$?" -ne "0" ]; then
        logger "The '$medium' is not available"
        return 1
    fi

#check if the imdr_debugs directory is present, if not create it
    ls $medium/imdr_debugs 1>/dev/null 2>/dev/null
    if [ "$?" -ne "0" ]; then
         echo "Couldnot find $medium/imdr_debugs..creating" >> /tmp/${proc}_imdr_abort_script_log
         mkdir -p $medium/imdr_debugs
    fi 

# Check if the dir is already present, if not create it.
    ls $dest_dir 1>/dev/null 2>/dev/null
    if [ "$?" -ne "0" ]; then
        echo "Couldnot find $dest_dir Creating" >> /tmp/${proc}_imdr_abort_script_log
        mkdir -p $dest_dir
    fi
fi

# Build the path of the filename to create
suffix=`date +%Y-%m-%d_%H-%M-%S`


filename="${proc}_imdr_abort_logs.${suffix}"

logger "Starting script '$filename' '$medium' '$proc'"

echo $filename >> /tmp/${proc}_imdr_abort_script_log
echo $dest_dir >> /tmp/${proc}_imdr_abort_script_log
 
if [ -f /pkg/bin/${proc}_imdr_abort_debug_script ]
then
    /pkg/bin/${proc}_imdr_abort_debug_script /tmp/$filename /tmp/${proc}_imdr_abort_script_log
else
    echo "${proc}_imdr_abort_debug_script doesn't exist" >> /tmp/${proc}_imdr_abort_script_log
    logger "${proc}_imdr_abort_debug_script doesn't exist "
    return 1
fi

cd /tmp
tar -cvf ${proc}_imdr_abort_logs.tar $filename >> /tmp/${proc}_imdr_abort_script_log 
gzip -c ${proc}_imdr_abort_logs.tar >> ${proc}_imdr_abort_logs.tar.gz
if [ "$?" -ne "0" ]; then
    echo "*** Unable to tar & gunzip \n" >> /tmp/${proc}_imdr_abort_script_log
    cp /tmp/$filename.${suffix} $dest_dir/.
fi


cp ${proc}_imdr_abort_logs.tar.gz ${proc}_imdr_abort_logs.tgz 

cp /tmp/${proc}_imdr_abort_logs.tgz $dest_dir/${proc}_imdr_abort_logs.${suffix}.tgz
if [ "$?" -ne "0" ]; then
    echo "*** Unable to Copy tgz file to destination\n" >> /tmp/${proc}_imdr_abort_script_log
fi


#Collect the progress of the script
filename="/$dest_dir/script_status_${proc}.${suffix}" 
echo "*** Start of script status collection\n" >> /tmp/${proc}_imdr_abort_script_log
echo "CMD: cp /tmp/${proc}_imdr_abort_script_log $filename \n" >> /tmp/${proc}_imdr_abort_script_log
cp /tmp/${proc}_imdr_abort_script_log $filename 

logger "Completed collecting ${proc} imdr_abort logs" 

# Now do some housekeeping of the debug files on the harddisk for this node.
# Make sure that we don't go over the limit of allowing only 5 hbloss files
# If we have 6 or more debug files, delete all but the 3 oldest and 2 newest
# debug files.
NEW_FILE_NUMS_LIMIT=1
OLD_FILE_NUMS_LIMIT=4
TOTAL_FILE_NUMS_LIMIT=$(($NEW_FILE_NUMS_LIMIT+$OLD_FILE_NUMS_LIMIT))

# Define the list of patterns that can make up i2c log filenames
PATTERN_LIST="${proc}_imdr_abort_logs"

for pattern in $PATTERN_LIST
do
    # Define an array of debug files, sorted in time increasing order. We need
    # to filter out the imdr abort common log files from the list 
    set -A debug_files `ls -tr $dest_dir/${pattern}* 2>/dev/null`

    # Find out the number of debug files we have
    file_num=${#debug_files[*]}

    # If we are over the limit of files allowed, remove the debug files
    if [ "$file_num" -gt "$TOTAL_FILE_NUMS_LIMIT" ]; then
        # 'k' is the index of the first "new" debug file that we are keeping
        # 'j' is the index of the file(s) that need to be removed
        k=$(($file_num-$NEW_FILE_NUMS_LIMIT))
        j=$OLD_FILE_NUMS_LIMIT
        while [ $j -lt $k ]
        do
            # Remove the debug file and its associated pcds file
            rm ${debug_files[$j]} 2>/dev/null
            j=$(($j+1))
        done
    fi
done

# Define the list of patterns that make up the script status log filenames 
PATTERN_LIST="script_status_${proc}"

for pattern in $PATTERN_LIST
do
    # Define an array of debug files, sorted in time increasing order. We need
    # to filter out the script status log files from the list
    set -A debug_files `ls -tr $dest_dir/${pattern}* 2>/dev/null`

    # Find out the number of debug files we have
    file_num=${#debug_files[*]}

    # If we are over the limit of files allowed, remove the script status files
    if [ "$file_num" -gt "$TOTAL_FILE_NUMS_LIMIT" ]; then
        # 'k' is the index of the first "new" debug file that we are keeping
        # 'j' is the index of the file(s) that need to be removed
        k=$(($file_num-$NEW_FILE_NUMS_LIMIT))
        j=$OLD_FILE_NUMS_LIMIT
        while [ $j -lt $k ]
        do
            # Remove the debug file and its associated pcds file
            rm ${debug_files[$j]} 2>/dev/null
            j=$(($j+1))
        done

    fi
done
