#!/bin/bash 

#
# Copyright (c) 2018 Engineering Design Team (EDT), Inc.
# All rights reserved.
#
# This file is subject to the terms and conditions of the EULA defined at
# www.edt.com/terms-of-use
#
# Technical Contact: <tech@edt.com>
#

#
# Usage (in terminal/script): ./edt_check_board_order <path/to/>edt_lnx_kernel.c <path/to/>edtinit
#
# Run as a tool to verify that the contents of the EDT Device Table at edtinit::edt_board_id_set() 
#   match the contents of the list located ar edt_lnx_kernel.c::edt_find_boards(). These lists
#   absolutly must have the exact same ordering to ensure proper device load order and 
#   functionality. Verifying that order is the purpose of this script.
#
# Exits:
#   0: success, the order of the boards within the files match
#   1: failure, the order of the boards within the files differs
#   2: failure, incorrect parameters
#


#
# Save files (with absolute path).
#
file_kern=""
file_init=""
save_kern=/tmp/find_board-edt_lnx_kernel.txt
save_init=/tmp/find_board-edtinit.txt

if [ $# -ne 2 ]; then
  echo "ERROR: incorrect parameter count; this script requires the following input:"
  echo "  edt_check_board_order <path/to/>edt_lnx_kernel.c <path/to/>edtinit"
  exit 2
else 
  file_kern="$1"
  file_init="$2"
fi

#
# Gather the IDs list from edt_lnx_kernel.c.
#
begin="nboards +="
end="return nboards;"

# Get only the lines between '$begin' and '$end', removing empty lines and return statement.
sed -n "/$begin/,/$end/p" $file_kern | sed '/^$/d; /return.*/d' |\
  # Trim results further so only the Edt Device IDs (without '_ID' are in the file '$save'.
  sed 's/^.*(//; s/_ID.*//' >$save_kern

#
# Gather 'Board IDs' table column from edtinit.
#
begin="edt_board_id_set=("
end=") # end edt_board_id_set table"

# Get only the lines between '$begin' and '$end', removing comments and begin/end array lines.
sed -n "/$begin/,/$end/p" $file_init | sed "/$begin/d; /$end/d" | sed '/^$/d; /^\t*#.*/d; /^ *#.*/d' |\
  # Trim results further so only the 'Board Name' column entries are in the file '$save'.
  sed 's/^\t*//; s/:.*//; s/".*  *//' >$save_init

#
# Compare the IDs ordering between the two newly created $save_* files (displaying results for user).
#
result=`diff -u $save_kern $save_init`

#
# Remove the $save_* files
#
#rm $save_kern
#rm $save_init

if [[ ! -z "$result" ]]; then
  echo "edt_check_board_order FAILED; mismatch between the board order in the following"
  echo "  files: '$file_kern' and '$file_init'."
  echo ""
  echo "$result"
  exit 1 
else
  exit 0
fi 
