#!/bin/bash

DR1_CHANNEL=1
DR2_CHANNEL=2
EMU_DR3_CHANNEL=3
EMU_DR4_CHANNEL=4
BDY1_CHANNEL=5
EMU_BDY2_CHANNEL=6
AI_CHANNEL=8
DIAG_CHANNEL=9

trap endlog INT
endlog() {
  echo ""
  echo "Cleaning up and creating logs..."
  log2asc -I $raw_can_log -O $diag_asc_file DIAG_CAN
  sed -i "s/\(^[[:space:]]\+[[:digit:]]\+\.[[:digit:]]\+\) 1 \(.*\)/\1 $DIAG_CHANNEL \2/g" $diag_asc_file
  log2asc -I $raw_can_log -O $ai_asc_file AI_CAN
  sed -i "s/\(^[[:space:]]\+[[:digit:]]\+\.[[:digit:]]\+\) 1 \(.*\)/\1 $AI_CHANNEL \2/g" $ai_asc_file
  log2asc -I $raw_can_log -O $dr1_asc_file DR_CAN1
  sed -i "s/\(^[[:space:]]\+[[:digit:]]\+\.[[:digit:]]\+\) 1 \(.*\)/\1 $DR1_CHANNEL \2/g" $dr1_asc_file
  log2asc -I $raw_can_log -O $dr2_asc_file DR_CAN2
  sed -i "s/\(^[[:space:]]\+[[:digit:]]\+\.[[:digit:]]\+\) 1 \(.*\)/\1 $DR2_CHANNEL \2/g" $dr2_asc_file
  log2asc -I $raw_can_log -O $bdy1_asc_file BDY_CAN1
  sed -i "s/\(^[[:space:]]\+[[:digit:]]\+\.[[:digit:]]\+\) 1 \(.*\)/\1 $BDY1_CHANNEL \2/g" $bdy1_asc_file
  log2asc -I $raw_can_log -O $emu_bdy2_asc_file EMU_BDY_CAN2
  sed -i "s/\(^[[:space:]]\+[[:digit:]]\+\.[[:digit:]]\+\) 1 \(.*\)/\1 $EMU_BDY2_CHANNEL \2/g" $emu_bdy2_asc_file
  log2asc -I $raw_can_log -O $emu_dr3_asc_file EMU_DR_CAN3
  sed -i "s/\(^[[:space:]]\+[[:digit:]]\+\.[[:digit:]]\+\) 1 \(.*\)/\1 $EMU_DR3_CHANNEL \2/g" $emu_dr3_asc_file
  log2asc -I $raw_can_log -O $emu_dr4_asc_file EMU_DR_CAN4
  sed -i "s/\(^[[:space:]]\+[[:digit:]]\+\.[[:digit:]]\+\) 1 \(.*\)/\1 $EMU_DR4_CHANNEL \2/g" $emu_dr4_asc_file

  echo "Created ASC log files at $dirname"
  echo "These logs are viewable via the CANalyzer config at firmware/tools/vector/canalyzer/vh6b/emu_log_player.cfg"
  exit 0
}

display_help() {
  echo "Usage: $0 [-h] [DIR]"
  echo
  echo "  -h  -- Display this help message and exit."
  echo "  DIR -- Optional directory to output CAN logs to. Will be created if it does not exist."
  echo
  exit $1
}

if [[ $1 = "-h" ]]
  then
    display_help 0
elif [[ $# -gt 1 ]]
  then
    echo "Too many arguments!"
    display_help 1
elif [[ $# -eq 1 ]]
  then
    dirname=$1
else
  nowdate=$(date +%m%d%y_%H%M%S)
  dirname="can_logs_${nowdate}"
fi

rawlogdir=$dirname/raw_logs
echo "Creating directory $dirname..."
mkdir -p $rawlogdir

raw_can_log=$rawlogdir/raw_can_log.log
diag_asc_file=$dirname/diag_can.asc
ai_asc_file=$dirname/ai_can.asc
dr1_asc_file=$dirname/dr1_can.asc
dr2_asc_file=$dirname/dr2_can.asc
bdy1_asc_file=$dirname/bdy1_can.asc
emu_bdy2_asc_file=$dirname/emu_bdy2_can.asc
emu_dr3_asc_file=$dirname/emu_dr3_can.asc
emu_dr4_asc_file=$dirname/emu_dr4_can.asc

( (candump -L AI_CAN DIAG_CAN DR_CAN1 DR_CAN2 BDY_CAN1 EMU_BDY_CAN2 EMU_DR_CAN3 EMU_DR_CAN4) 1>$raw_can_log)  &
P1=$!

echo "Logging CAN..."
echo "Press Ctrl-C to exit"

wait $P1
