#################################################################################
# SCRIPT LOGGING CONFIGURATION
#
# The following is used by the script to output log data. Depending upon the log
# level indicated, more or less data may be output, with a "lower" level
# providing more detail, and the "higher" level providing less verbose output.
#################################################################################
dateTime="`date +%Y-%m-%d` `date +%T%z`" # Date format at beginning of log entries to match RFC
dateForFileName=`date +%Y%m%d`

logFolder="${HOME}/installation"
logFile="${logFolder}/install.log"

touch "$logFile"
sudo chmod a+rw "$logFile"

# Defines log levels
declare -A logPriorities=([DEBUG]=0 [INFO]=1 [WARN]=2\
 [ERROR]=3 [NONE]=4)

# Default log level
scriptLoggingLevel="INFO"
#################################################################################
#          ##      END OF GLOBAL VARIABLE CONFIGURATION      ##
#################################################################################
# LOGGING
#
# Calls to the logThis() function will determine if an appropriate log file
# exists. If it does, then it will use it, if not, a call to openLog() is made,
# if the log file is created successfully, then it is used.
# As third argument, you can pass false or true depending on if you want the log to also be outputed to standard output
# (witout added information so it can be displayed on zenity window)
#
# All log output is comprised of
# [+] An RFC 3339 standard date/time stamp
# [+] The declared level of the log output
# [+] The runtime process ID (PID) of the script
# [+] The log message
#################################################################################
function openLog {
    echo -e "${dateTime} : PID $$ : INFO : New log file (${logFile}) created." >> "${logFile}"

    if ! [[ "$?" -eq 0 ]]
    then
        echo "${dateTime} - ERROR : UNABLE TO OPEN LOG FILE"
        return 1
    fi
}

function logThis() {
    dateTime=$(date --rfc-3339=seconds)

    if [[ -z "${1}" ]]; then
        echo "${dateTime} - ERROR : LOGGING REQUIRES A MESSAGE AND A PRIORITY, IN THAT ORDER."
        echo "${dateTime} - ERROR : INPUTS WERE: ${1} and ${2}."
        return 1
    fi

    if [[ -z "${2}" ]]; then
        logMessagePriority="DEBUG"
    else
        logMessagePriority=${2}
    fi

    if [[ ${3} == false ]]; then
        logToOutput=false
    else
        logToOutput=true
    fi

    logMessage="${1}"

    [[ ${logPriorities[$logMessagePriority]} ]] || return 1
    (( ${logPriorities[$logMessagePriority]} < ${logPriorities[$scriptLoggingLevel]} )) && return 2

    if [[ $logMessagePriority == ${logPriority[NONE]} ]]; then
        return 0
    fi

    # No log file, create it.
    if ! [[ -f ${logFile} ]]
    then
        echo -e "INFO : No log file located, creating new log file (${logFile})."
        echo "${dateTime} : PID $$ :INFO : No log file located, creating new log file (${logFile})." >> "${logFile}"
        openLog
    fi

    # Write log details to file
    echo -e "${dateTime} : PID $$ : ${logMessagePriority} : ${logMessage}" >> "${logFile}"

    if [[ $logToOutput == true ]]; then
        echo "${logMessage}"
    fi
}

# Functions using stdin
function logDebug() {
    while read data; do
        logThis "$data" DEBUG
    done
}

function logInfo() {
    while read data; do
        logThis "$data" INFO
    done
}

function logWarn() {
    while read data; do
        logThis "$data" WARN
    done
}

function logError() {
    while read data; do
        logThis "$data" ERROR
    done
}

function purgeLogs(){

    limitDateStr=${1}

    if [[ -z ${limitDateStr} ]]; then
        limitDateStr="`date +%Y-%m-%d -d "1 year ago"`"
    fi

    limitDate=`date +%s -d "${limitDateStr}"`
    result=$?
    if [[ $result != 0 ]]; then
        echo "Invalid limite date : ${limitDateStr}, error code : $result"
        return $result
    fi

    logFilePath="${HOME}/installation_history.log"
    lastDateStr=`head -1 "${logFilePath}" | grep -Po ".*(?=\s:\sP)"`
    lastDate=`date +%s -d "${lastDateStr}"`
    result=$?
    if [[ $result != 0 || -z $lastDateStr ]]; then
        echo "Invalid date in log file ${logFilePath}, date in first line : ${lastDateStr}, result code : $result"
        return $result
    fi

    logThis "limitDate : ${limitDate}" "DEBUG"
    logThis "lastDate : ${lastDate}" "DEBUG"
    
    (( $limitDate >= $lastDate ))
    result=$?
    if [[ $result == 0 ]]; then
        logThis "Purging log file : ${logFilePath}" "INFO"
        truncate -s 0 ${logFilePath}
    fi

    return 0
}