#!/bin/bash

LOG_DIR=/home/celestia/.HEMISPHERE
CAN_LOG_FILE_BASE=can_traffic

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

if [ -x /bin/can_server ]; then
    ulimit -c unlimited
    ulimit -a

    read KEY < /sys/class/net/eth0/address
    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

    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
    fi

    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

    CAN_LOG_FILENAME=${CAN_LOG_FILE_BASE}_${MAC}_${INDEX}.log

    CAN_LOG_FILE=${LOG_DIR}/${CAN_LOG_FILENAME}

    exec /bin/can_server --log ${CAN_LOG_FILE} --log-level 0

    echo -e "can_server executable done!"
    #todo maybe add a sleep hack here so that we can Set the LED colour based on both can_server and Controller
    /bin/SetUIDRunner SetGPO comled off
    #todo encyrpt dmesg
    dmesg > $LOG_DIR/can_server.dmesg
    cp /var/log/syslog $LOG_DIR/can_server.syslog
else
    echo -e "can_server executable not found"
fi
