#!/bin/bash


################################################################################
# Variables                                                                    #
################################################################################
WORK_FILES_DIR=/mnt/persistent-data/evtec-ecp-data
MAX_LOG_FILES=10
UID_GID="xfc:xfc"
MAX_LOG_ROWS=500


################################################################################
# Functions                                                                    #
################################################################################
# It checks if the ENV Variable $ECP_WORK_FILES_DIR exist.
# If not the variable is exported
handleEvtecWorkDir()
{
    # Check if a path in ECP_WORK_FILES_DIR is given
    if [[ -z "$ECP_WORK_FILES_DIR" ]]; then
        export ECP_WORK_FILES_DIR=$WORK_FILES_DIR
    fi
}

# uild the path string with the $ECP_WORK_FILES_DIR env variable.
definePaths()
{
    PATH_DMESG_LOGS="${ECP_WORK_FILES_DIR}"/log/dmesg-logs
    PATH_JOURNALCTL_LOGS="${ECP_WORK_FILES_DIR}"/log/journalctl-logs
    LOG_PATHS=("${PATH_DMESG_LOGS}" "${PATH_JOURNALCTL_LOGS}")
}

# If the log folders does not exist, it creates it.
createLogFolders()
{
    for path in "${LOG_PATHS[@]}"; do
        if [ ! -d "$path" ]; then
            mkdir $path -p
        fi
    done
}

# puts the content of journalctl and dmesg into file in the log folder.
storeSystemLogs()
{
    system_timestamp=$(date +"%d%m%y-%T")
    journalctl -r -n $MAX_LOG_ROWS > "${ECP_WORK_FILES_DIR}"/log/journalctl-logs/${system_timestamp}_journalctl-on-error.log
    dmesg | tail -n $MAX_LOG_ROWS > "${ECP_WORK_FILES_DIR}"/log/dmesg-logs/${system_timestamp}_dmesg-on-error.log
}

# Check the amount of the files, if there are more then MAX_LOG_FILES, the oldest ones will be deleted.
rotateLogFiles()
{
    for path in "${LOG_PATHS[@]}"; do
        files=($(ls -t "$path"))
        count=${#files[@]}

        if [ $count -gt $MAX_LOG_FILES ]; then
            for (( i=$MAX_LOG_FILES; i<$count; i++ )); do
                rm "$path/${files[$i]}"
            done
        fi
    done
}

# Change permission so other non-root applications can access it (DeviceMaintenanceServer)
changePermissions()
{
    for path in "${LOG_PATHS[@]}"; do
        chown -R $UID_GID $path/
    done
}

################################################################################
# Main entry                                                                   #
################################################################################
handleEvtecWorkDir
definePaths
createLogFolders
storeSystemLogs
rotateLogFiles
changePermissions
