#!/bin/bash
#set -x

if [ "$HAS_DEBUGGING_FUNCTIONS" != "yes" ]; then
. /etc/ags-celestia/debugging_functions
fi

if [ "$HAS_LPC_FIRMWARE_FUNCTIONS" != "yes" ]; then
. /etc/ags-celestia/lpc_firmware_functions
fi

HAS_CAN_MESSAGING_FUNCTIONS="yes"

PCAN_MESSAGE_EXE="transmitest"
PCAN_MESSAGE_EXE_PARAMS="-f=/dev/pcan0 -b=0x011c -e -q"
 
# There are potential name clashes everywhere here
# with other scripts that will call this one!!
# Prefixing these var's with CMF (can_message_functions)
# Also, if there is a snazzy_can_tx avail in /tmp we are going to
# use it, since it has been put there by install_release.sh to help 
# with downgrade issues.
CMF_TEMP_SNAZZY_CAN_MESSAGE_EXE="/tmp/snazzy_can_tx"
CMF_SNAZZY_CAN_MESSAGE_EXE="/usr/local/bin/snazzy_can_tx"
if [ -f $CMF_TEMP_SNAZZY_CAN_MESSAGE_EXE ]; then
    CMF_SNAZZY_CAN_MESSAGE_EXE=$CMF_TEMP_SNAZZY_CAN_MESSAGE_EXE
fi
CMF_SNAZZY_CAN_MESSAGE_EXE_PARAMS="-0 -q"

CMF_CAN_MESSAGE_EXE=""
CMF_CAN_MESSAGE_EXE_PARAMS=""
CMF_CAN_MESSAGE_CMD=""

function init_can_messaging_commands
{
    debug_function "init_can_messaging_commands"

    init_lpc_firmware_functions

    # If /proc/lpcusbcan2 exists, we have the old PCAN based firmware
    if [ -f /proc/lpcusbcan2 ]; then
        which $PCAN_MESSAGE_EXE > /dev/null 2>&1

        result=$?

        if [ $result -eq 0 ]; then
            CMF_CAN_MESSAGE_EXE=${PCAN_MESSAGE_EXE}
            CMF_CAN_MESSAGE_EXE_PARAMS=${PCAN_MESSAGE_EXE_PARAMS}
        else
            echo "PANIC! Required binary \"${PCAN_MESSAGE_EXE}\" not found!"
            exit 1
        fi
    else
        # The snazzy_can_tx script now handles using the correct executable
        CMF_CAN_MESSAGE_EXE=${CMF_SNAZZY_CAN_MESSAGE_EXE}
        CMF_CAN_MESSAGE_EXE_PARAMS=${CMF_SNAZZY_CAN_MESSAGE_EXE_PARAMS}
    fi 
 
    CMF_CAN_MESSAGE_CMD="${CMF_CAN_MESSAGE_EXE} ${CMF_CAN_MESSAGE_EXE_PARAMS}"
}

function init_serial_messaging_commands
{
    debug_function "init_serial_messaging_commands"

    stty -F /dev/ttyS1 speed 115200 rows 0 columns 0 line 0 intr ^C quit ^\\ erase ^\? kill ^U eof ^D start ^Q stop ^S susp ^Z rprnt ^R werase ^W lnext ^V flush ^O min 0 time 246 -parenb -parodd cs8 -hupcl -cstopb cread clocal -crtscts -ignbrk -brkint -ignpar -parmrk -inpck -istrip -inlcr -igncr -icrnl -ixon -ixoff -iuclc -ixany -imaxbel -iutf8 -opost -olcuc -ocrnl -onlcr -onocr -onlret -ofill -ofdel nl0 cr0 tab0 bs0 vt0 ff0 -isig -icanon -iexten -echo echoe echok -echonl -noflsh -xcase -tostop -echoprt echoctl echoke
}

# @param $1 message file to transmit
function send_can_message
{
    debug_function "send_can_message"

    local MESSAGE_FILE=$1

    # Check the CAN messaging command variables have been initialised
    if [ "x${CMF_CAN_MESSAGE_CMD}" = "x" ]; then
        # If not, initialise them
        init_can_messaging_commands
    fi

    # Check the message file name has been passed and is a valid file
    if [ "x${MESSAGE_FILE}" != "x" ]; then
        if [ -r $MESSAGE_FILE ]; then
            # Send the message
            $CMF_CAN_MESSAGE_CMD $MESSAGE_FILE > /dev/null 2>&1
        fi
    fi
}

# @param $1 update state 
# @param $2 state progress percent
function send_update_progress_message
{
    debug_function "send_update_progress_message"

    local MSG_ID_HEX=$(printf "0x%02x" $1)
    local PERCENT_HEX=$(printf "0x%02x" $2)

    # Generate a temporary file name
    local MSG_SCRIPT=$(tempfile -p update_progress -s .msg )

    # Generate the message using the temporary file name
    cat > $MSG_SCRIPT <<EOF 
m e 0x0cef1c1d 5 0x80 0x0b 0x87 $PERCENT_HEX $MSG_ID_HEX 
EOF

    # Send the message
    send_can_message $MSG_SCRIPT

    # Delete the temporary file
    rm $MSG_SCRIPT

    cat > $MSG_SCRIPT <<EOF 
m e 0x0cef1c1d 8 0x40 0xb2 $PERCENT_HEX 0x0 0x0 0x0 0x0 0x0
EOF

    # Send the message
    send_can_message $MSG_SCRIPT

    # Delete the temporary file
    rm $MSG_SCRIPT

    #Serial
    echo -e "$>ECU,update/percent,"$2\\r\\n > /dev/ttyS1

}

# @param $1 status message id to send
function send_status_message
{
    debug_function "send_status_message"

    local PARAM=$( printf "%02x" $1)
    PARAM_HEX=$( printf "0x%02x" $1)

    # Generate a temporary file name
    MSG_SCRIPT=$(tempfile -p ecu_status -s .msg )

    # Generate the message using the temporary file name
    cat > $MSG_SCRIPT <<EOF 
m e 0x0cef1c1d 4 0x80 0x0b 0x88 $PARAM_HEX
EOF

    # Send the message
    send_can_message $MSG_SCRIPT

    # Delete the temporary file
    rm $MSG_SCRIPT

    # Generate the message using the temporary file name
    cat > $MSG_SCRIPT <<EOF 
m e 0x0cef1c1d 8 0x40 0xb9 $PARAM_HEX 0x0 0x0 0x0 0x0 0x0
EOF

    # Send the message
    send_can_message $MSG_SCRIPT

    # Delete the temporary file
    rm $MSG_SCRIPT

    if [ "x$PARAM" == "x00" ]; then
      echo -e "$>ECU,status/power,off"\\r\\n > /dev/ttyS1
    elif [ "x$PARAM" == "x01" ]; then
      echo -e "$>ECU,status/power,on"\\r\\n > /dev/ttyS1
    fi
}
