#!/bin/bash

LOG_DIR=/home/celestia/.HEMISPHERE
BACKUP_DIR=${LOG_DIR}/bup
CAN_LOG_FILE_BASE=can_

if [ ! -d ${LOG_DIR} ]; then                                    # if log dir doens't exist
    mkdir ${LOG_DIR}                                            # make it
fi

START_DIR=$(pwd)                                                # determine the starting directory
cd ${LOG_DIR}                                                   # change directory to log dir

MIN_FREE_SPACE=800000                                           # min free space that triggers the cleanup is 800mb (df shows size in 1KB blocks)
MAX_SPACE_TO_FREE=204800                                        # max space to free up in one cleanup
DISK_FREE=$(df | awk '/\/$/ {print $4}')                        # determine free disk space by getting df output for the disk mounted at '/'
if [ ${DISK_FREE} -lt $MIN_FREE_SPACE ]; then                   # if free disk space is less than MIN_FREE_SPACE
    FREE_SPACE_AFTER_CLEANUP=$((${DISK_FREE} + ${MAX_SPACE_TO_FREE})) # after cleanup the free disk space should be no less than current free space plus MAX_SPACE_TO_FREE
    FIRST_PASS=1
    while [ ${DISK_FREE} -lt ${FREE_SPACE_AFTER_CLEANUP} ] ; do # loop while free disk space is less than FREE_SPACE_AFTER_CLEANUP
        if [ ${FIRST_PASS} -eq 1 ] ; then
            FIRST_PASS=0
            SetUIDRunner rmLogs /var/log/*.[0-9]*
        else
            OLDEST_TGZ=$(echo $(ls *.tgz) | awk '{print $1}')   # determine which .tgz file is oldest (has the smallest index number)
            if [ "${OLDEST_TGZ}" != "" ] ; then                 # if oldest .tgz exists
                rm -f ${OLDEST_TGZ}                             # delete the oldest .tgz file
                if [ $? -ne 0 ] ; then                          # if rm failed
                    echo -e "Celestia: Cannot remove ${OLDEST_TGZ}. Don't know what to do here!"
                    break
                fi
            else
                rm -f sys_dbg_*.log cont_dbg_*.log data_timing_*.log user_logs.csv # since no .tgz file is found, delete sys_dbg_*.log, cont_dbg_*.log and data_timing_*.log
                rm -f ${CAN_LOG_FILE_BASE}*.log*                # since no .tgz file is found, delete CAN logs
                break                                           # break out of while loop since there is nothing more we can do to free up disk space
            fi
        fi
        sync                                                    # sync to make sure df returns current status
        DISK_FREE=$(df | awk '/\/$/ {print $4}')                # update free disk space by getting df output for the disk mounted at '/'
    done
fi

read KEY < /sys/class/net/eth0/address                          # read system's MAC address
echo "${KEY}" | encfs -S /home/celestia/.bak /home/celestia/dm  # used the MAC address to decrypt the Controller
if [ -x /home/celestia/dm/Controller ]; then                    # check for the Controller executable
    rm -rf ${BACKUP_DIR}                                        # remove any existing temporary backup directory
    mkdir ${BACKUP_DIR}                                         # create temporary directory to use for backing up logs
    mv sys_dbg_*.log ${BACKUP_DIR}                              # move sys_dbg_*.log, cont_dbg_*.log and data_timing_*.log
    mv cont_dbg_*.log ${BACKUP_DIR}                             # to temporary directory
    mv data_timing_*.log ${BACKUP_DIR}
    mv user_logs.csv ${BACKUP_DIR}
    mv ${CAN_LOG_FILE_BASE}*.log* ${BACKUP_DIR}
    cp Celestia.ini* ${BACKUP_DIR}                              # copy Celestia.ini* to temporary directory
    mv core_* ${BACKUP_DIR}                                     #collect all core dump files
    mv *.dmesg ${BACKUP_DIR}                                    #collect any dmesg dumps
    mv *.syslog ${BACKUP_DIR}                                   #collect any syslog dumps

    (nice /bin/backup_celestia_logs ${LOG_DIR} ${BACKUP_DIR}) & # start backup process in background and nice it to an appropriately low priority

    N=0
    LAST_INDEX_FILE=$(echo $(ls -r index_*) | awk '{print $1}') # determine which index_* file is newest (has the largest index number - there should only be one)
    if [ "${LAST_INDEX_FILE}" != "" ] ; then
        N=$(echo "${LAST_INDEX_FILE}" | sed -e 's/index_\([0-9]*\)/\1/') # extract the index number from the index_* file
        N=$((${N} + 1))                                         # increment it by 1 to get the next index number
        mv ${LAST_INDEX_FILE} index_${N}
    else
        touch index_${N}
    fi

    cd $START_DIR                                               # change directory back to start dir
    if [ -x /bin/reset_dmu ]; then                              # if reset_dmu application exists and is executable
        /bin/reset_dmu                                          # reset the dmu
        sleep 10
    fi

    CONFIG_FILE=/etc/ags-celestia/config.xml
    MAC=$(cat /sys/class/net/eth0/address | sed -e 's/://g')    # read MAC address and strip ':' out of it so that it can be used in the file name
    INDEX="a$(echo ${N} | awk '{printf("%08d",$0)}')"           # create an index by padding N with an a and leading zeros to make nine characters that will cause new files to be listed after the old files
    echo "MAC Adress: ${KEY}" > ${LOG_DIR}/sys_dbg_${MAC}_${INDEX}.log # start sys_dbg_'MAC address'_'index'.log with system's MAC address
    echo "MAC Adress: ${KEY}" > ${LOG_DIR}/cont_dbg_${MAC}_${INDEX}.log # start cont_dbg_'MAC address'_'index'.log with conttem's MAC address
    echo "MAC Adress: ${KEY}" > ${LOG_DIR}/data_timing_${MAC}_${INDEX}.log # start data_timing_'MAC address'_'index'.log with conttem's MAC address

    ulimit -c unlimited

    STORAGE_CONSOLIDATION_CONFIG_FILE=/etc/ags-celestia/config.xml.storage_consolidation
    /home/celestia/dm/Controller \
        -cfg ${STORAGE_CONSOLIDATION_CONFIG_FILE} \
        -dbg file:${LOG_DIR}/sys_dbg_${MAC}_${INDEX}.log:a \
            "*=0x3c"
    echo -e "Celestia: Storage consolidation done!"
    sync
    echo -e "Sync done!"

    # start Controller with sys_dbg, cont_dbg and data_timing logs (make sure they are not truncated)
    /home/celestia/dm/Controller \
        -cfg ${CONFIG_FILE} \
        -dbg file:${LOG_DIR}/sys_dbg_${MAC}_${INDEX}.log:a \
            "*=0x243c" \
            SYSTEM_METRICS=0x8000 \
        -dbg file:${LOG_DIR}/cont_dbg_${MAC}_${INDEX}.log:a \
            "*=0x0" \
            Main=0x400 \
            VehicleKinematicsEstimator=+DBG_CONT_LOG \
        -dbg file:${LOG_DIR}/data_timing_${MAC}_${INDEX}.log:a \
            "*=0x000"
    echo -e "Celestia: Controller executable done!"
    /bin/SetUIDRunner SetGPO comled off
    #todo encyrpt dmesg
    dmesg > $LOG_DIR/Controller.dmesg
    cp /var/log/syslog $LOG_DIR/Controller.syslog
else
    echo -e "Celestia: Controller executable not found"
fi

fusermount -q -u /home/celestia/dm                              # controller done, unmount encrypted fs.

