#!/bin/bash

COMM_SCRIPTDIR=$(cd "$(dirname "$0")" && pwd)

function zipLog()
{
    local logName=$1
    if [ ! -f "$logName" ];then
        return
    fi

    local MAXLOGSIZE=10485760
    local LOGFILE_SUFFIX="gz"
    local LOG_FILE_PATH=`dirname "$logName"`
    local LOG_FILE_NAME_USE=`basename "$logName"`
    local BACKLOGCOUNT=`ls -l ${LOG_FILE_PATH} | grep "${LOG_FILE_NAME_USE}" | grep ${LOGFILE_SUFFIX}$ |wc -l`

    local LOGFILESIZE=`ls -l "$logName" | awk -F " " '{print $5}'`
    if [ ${LOGFILESIZE} -gt ${MAXLOGSIZE} ]
    then
        gzip -f -q -9 "$logName"
        local FILENAME_DATE=`date +"%y-%m-%d-%H:%M:%S"`
        local srcName="$logName.${LOGFILE_SUFFIX}"
        local destName="$logName.${FILENAME_DATE}.${LOGFILE_SUFFIX}" 
        mv "$srcName" "$destName"
        chmod 440 "$destName" &>/dev/null 
    fi
    
    if [ $BACKLOGCOUNT -gt 10 ]
    then
        local cur_path=`pwd`
        cd "${LOG_FILE_PATH}"
        local deleteLogName=`ls ${LOG_FILE_NAME_USE}* |sort | sed -n "2p"`
        rm -rf ${deleteLogName}
        pushd "$cur_path" &>/dev/null
    fi
}

function Log()
{
    LOG_FILE_PATH=`dirname ${LOG_FILE_NAME}`
    if [ ! -x "${LOG_FILE_PATH}" ]
    then
        mkdir ${LOG_FILE_PATH}
        chmod 750 "${LOG_FILE_PATH}"
        chmod g+s "${LOG_FILE_PATH}"
    fi
    
    if [ ! -f "${LOG_FILE_NAME}" ]
    then
        touch "${LOG_FILE_NAME}" 
    fi
    chmod 640 "${LOG_FILE_NAME}"
    
    DATE=[`date +"%Y/%m/%d %H:%M:%S"`]
    USER_NAME=`whoami`
    echo "${DATE}:[$$][${USER_NAME}] $1" >> "${LOG_FILE_NAME}"
    zipLog "$LOG_FILE_NAME"
}

function getClassPath()
{
    local LIBS="$1"
    local LIBS_PATH="$2"
    classList=
    if [ "$LIBS_PATH" = "" ]
    then
        LIBS_PATH=lib
    fi
    
    if [ -z "$LIBS" ];then
        return 1
    fi 
    local cur=`pwd`
    pushd "$COMM_SCRIPTDIR" &>/dev/null
    libsList=`echo $LIBS | sed 's/ /\*/g' | sed 's/;/ /g'`
    for libFile in  $libsList
    do
        fileName=`ls "$LIBS_PATH/$libFile"*`
        classList=$classList:$fileName    
    done
    CLASSPATH=`echo ${classList:1}`
    pushd "$cur" &>/dev/null
}

Chattr() {
	opt="$1"
	if [ "$opt" = "" ]; then
		exit 1
	fi
	shift
	path=`echo "$1"|sed 's/\/$//'`
	shift
	if [ ! -d "$path" ]; then
		exit 1
	fi
	find "$path" -user root -type f -executable | grep -v '/ha/module/' | while read line
	do
		chattr "$opt" "$line"
	done
}
LockRootScript() {
	trap "" EXIT
	for path in "$@"
	do
		Chattr +i $path
	done
}
UnlockRootScript() {
	for path in "$@"
	do
		Chattr -i $path
	done
}
