#!/bin/bash

if [ $# -lt 2 ] ; then                                          # if script is started without the two required parameters
    echo -e "Celestia: $(basename $0) must only be started from the run_celestia.sh script"
    exit 1
fi

LOG_DIR=$1
BACKUP_DIR=$2
N=0

CAN_LOG_FILE_BASE=can_

DoBackup ()
{
    local tag
    tag=$1
    mv user_logs.csv user_logs_${tag}.csv
    # tar sys_dbg_*.log, cont_dbg_*.log, data_timing_*.log and Celestia.ini* into controller_logs_'date tag'_'index'.tgz
    tar -czf controller_logs_${tag}.tgz sys_dbg_*.log \
        cont_dbg_*.log \
        data_timing_*.log \
        ${CAN_LOG_FILE_BASE}*.log* \
        user_logs_*.csv \
        Celestia.ini* \
        core_* \
        *.dmesg \
        *.syslog
    mv controller_logs_${tag}.tgz ${LOG_DIR}                    # move the newly created .tgz file to log dir
}

cd ${BACKUP_DIR}                                                # change directory to temporary directory
if [ "$(ls)" != "" ] ; then                                     # if directory is not empty
    TAG=$(echo $(ls -r cont_dbg_*.log) | awk '{print $1}' | sed -e 's/cont_dbg_\(..*\)\.log/\1/') # extract the tag from the control logs
    if [ "${TAG}" = "" ] ; then
        TAG=$(echo $(ls -r sys_dbg_*.log) | awk '{print $1}' | sed -e 's/cont_dbg_\(..*\)\.log/\1/') # extract the tag from the system logs
        if [ "${TAG}" != "" ] ; then
            DoBackup ${TAG}
        fi
    else
        DoBackup ${TAG}
    fi
fi

cd ${LOG_DIR}
rm -rf ${BACKUP_DIR}                                            # remove backup dir since backup is completed

