#!/bin/bash

COMM_SCRIPTDIR=$(cd "$(dirname "$0")" && pwd)
ALL_CLASS_PATH="$COMM_SCRIPTDIR/lib/*"

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

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

    local -r LOGFILESIZE=$(ls -l "$logName" | awk -F " " '{print $5}')
    if [ "${LOGFILESIZE}" -gt ${MAXLOGSIZE} ]
    then
        gzip -f -q -9 "$logName"
        local -r 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 -r cur_path=$(pwd)
        cd "${LOG_FILE_PATH}"
        local -r 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}"
    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"
}

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
}
