#!/bin/bash

osname=`uname`

#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#   Retrieves the log files in order of the version number.
function getFileList() {
    if [ "$osname" != "AIX" ]
    then
        /bin/ls -v -1 ${LogBase}*
    else
        /bin/ls -1 ${LogBase}*
    fi
}

#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#   Retrieves the log files in reverse order of the
#   version number.
function getFileListReverse() {
    if [ "$osname" != "AIX" ]
    then
        /bin/ls -v -r -1 ${LogBase}*
    else
        /bin/ls -r -1 ${LogBase}*
    fi
}

#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#   Returns the size of a file in MB.
#
#   arg 1: file name
function getFileSize() {
    if [ "$osname" != "AIX" ]
    then
        /bin/ls -s --block-size $ONE_MB $1 | awk '{print $1}'
    else
        typeset -i _sizeKB=`/bin/ls -s $1 | awk '{print $1}'`
        if [ $_sizeKB -lt 1000 ]
        then
            echo 1
        else
            typeset -i _sizeMB=`expr $_sizeKB / 1000`
            echo $_sizeMB
        fi
    fi
}

#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#   Returns the amount of available space for the /var
#   file system in MB.
function getAvailFSSpace() {
    typeset _sizeMB
    if [ "$osname" != "AIX" ]
    then
        typeset _size=$(df -k | grep $varDir | awk '{print $4}')
    else
        typeset _size=$(df -k | grep $varDir | awk '{print $3}')
    fi
    ((_sizeMB = _size * 1024 / ONE_MB))
    echo $_sizeMB
}

#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#   This function retrieves the maximum cimserver log file
#   size from the cim properties file. If the value is not
#   set or is not a valid number, the default value is
#   assigned.
function getMaxLogFileSize() {
    typeset -r _defaultLogSize=80
    typeset -i _size=`cat $CimPropFile |grep ^MaxCimServerLogSizeInMB`
    test -z "$_size" -o "$_size" -eq 0 && _size=$_defaultLogSize
    echo $_size
}

#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#   This function will check the available free space for
#   the /var file system. Log files will be deleted
#   until at least 5 X size of cimserver log size is free.
function checkSpace() {
    typeset _sizeMB=$(getAvailFSSpace)
    typeset _spaceNeeded

    ((_spaceNeeded = 5 * MaxLogFileSize))
    #  delete log files until there is enough free space
    if [[ "$_spaceNeeded" -gt "$_sizeMB" ]]; then
	# delete the last 
        typeset _deleteSize
        ((_deleteSize = _spaceNeeded - _sizeMB))
        typeset -r _logs=$(getFileListReverse)
        typeset _f
        for _f in $_logs; do
	    # compute file size in MB
            typeset _fs=$(getFileSize $_f)
            rm -f $_f
            ((_deleteSize -= _fs))
            if [[ "$_deleteSize" -le 0 ]]; then
                return
            fi
        done
    fi
}
	
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#   Returns the total amount of file space in MB for use
#   by the cimserver logs.
#   allow cimserver logs to utilize 25% of /var file system
function getLogSize() {
    typeset _size=$(df -k | grep $varDir | awk '{print $2}')
    typeset _logSize
    ((_logSize = _size * 1024 / ONE_MB / 4))
    echo $_logSize
}

#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#   This function will run gzip on any log files that are
#   not compressed.
function zipLogs() {
	typeset -r _logFiles=$(getFileListReverse)
	typeset _f
	for _f in $_logFiles; do
		file $_f | grep -q "gzip"
		if [[ $? -ne 0 ]]; then
			gzip -f $_f
		fi
	done
}

#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#   Rotates the exist log files in the archive directory.
function rotateLogs() {
    typeset -r _logFiles=$(getFileListReverse)
    typeset _version
    typeset _moveTo
    typeset _f
    for _f in $_logFiles; do
	# extract log version
        typeset _version=$(echo $_f | awk -F "." '{print $3}')
        ((_moveTo = _version + 1))
        mv -f $_f ${LogBase}${_moveTo}.gz
    done
}

#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function limitLogSize() {
    #+++++++++++++++++++++++++++
    #  get file list in version order
    typeset -r _logFiles=$(getFileList)
    typeset _f
    typeset -r _totalSize=$(getLogSize)
    typeset _size=0
    for _f in $_logFiles; do
        if [[ $_size -gt $_totalSize ]]; then
            #  delete archive
            rm -f $_f
        else
            typeset _fs=$(getFileSize $_f) 
            ((_size += _fs))
            if [[ $_size -gt $_totalSize ]]; then
                #  delete archive
                rm -f $_f
            fi
        fi
    done
}

#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#   Performs the archive of the latest log file. Other
#   actions are performed to make sure that the file system
#   does not become full.
function archiveLogFile() {
    #+++++++++++++++++++++++++++
    #  chdir to archive directory
    cd $ArchiveDir

    #+++++++++++++++++++++++++++
    #  before doing anything make sure there is available space
    checkSpace

    #+++++++++++++++++++++++++++
    #  check to see if log file is > max log size
    typeset -r _size=$(getFileSize $LogFile)
    test "$_size" -ge "$MaxLogFileSize" || return

    #+++++++++++++++++++++++++++
    #  make sure all log files are compressed
    zipLogs

    #+++++++++++++++++++++++++++
    #  now rotate existing logs
    rotateLogs

    #+++++++++++++++++++++++++++
    #  move cimserver log to archive directory
    mv -f ${LogFile} ${ArchiveDir}/${LogName}.1
    /opt/hsc/bin/startCIMServerLog
    gzip -f ${LogName}.1

    #+++++++++++++++++++++++++++
    #  limit the size of the cim logs
    limitLogSize
}

#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#   Performs the archive of the latest  VT log file.
function archiveVTLogFile() {
    #+++++++++++++++++++++++++++
    #  check to see if log file is > max log size
    typeset -r _size=$(getFileSize ${LogDir}/${VTLogName})

    typeset -r maxVT_size=60 

    test "$_size" -ge "$maxVT_size" || return

    typeset -r VTLogFile=${LogDir}/${VTLogName}
    if [ -a  $VTLogFile ]; then 
        cd $LogDir
        cp ${VTLogName} ${VTLogName}.1
        /opt/hsc/bin/truncate  -s 2 -f $VTLogFile
        gzip -f ${VTLogName}.1 
    fi

}
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#   Performs a first time setup for conversion of the
#   existing logs to the archive directory. Also compresses
#   all log files.
function firstTimeSetup() {
    cd ${LogDir}
    test -d ${ArchiveDir} && return
    mkdir ${ArchiveDir}
    mv -f ${LogBase}* ${ArchiveDir}
    cd $ArchiveDir
    zipLogs
}

#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#   This bash script will perform the archive of the cimserver logs.
#   It will perform the following tasks:
#      1) A first time setup is performed to create an archive directory
#         and move all existing cimserver logs to the archive directory.
#         After being moved, the log files will be compressed.
#      2) Before archiving the most recent cimserver log, the file space
#         on /var is checked to ensure there is 10 times the size of
#         the cimserver log available. Archive logs are deleted until
#         this condition is meet.
#      3) The archive logs are checked to ensure they are compressed.
#         Any uncompressed archive logs are compressed.
#      4) Archive logs are rotated up by one version.
#      5) The current cimserver log is moved to the archive directory.
#         A new instance of the cimserver log is started.
#      6) After archiving the current cimserver log, the total amount
#         of disk space consumed by the archive logs is checked. The logs
#         cannot exceed 25% of the available space on /var. Archive logs
#         are deleted until it conforms to this limit.

typeset -r CimPropFile=/opt/hsc/data/hmc.properties
typeset -r varDir="/var"
typeset -r ONE_MB=1000000
typeset -r LogDir=/var/hsc/log
typeset -r ArchiveDir=${LogDir}/cimLogs
typeset -r LogName="cimserver.log"
typeset -r LogFile=${LogDir}/${LogName}
typeset -r LogBase="${LogName}."
typeset -r MaxLogFileSize=$(getMaxLogFileSize)
typeset -r VTLogName="vterms.log"

firstTimeSetup
archiveLogFile
archiveVTLogFile
