#!/bin/bash
# Generate a keywords.txt for the library that is suitable for the Arduino IDE.
# Expects to run from the top directory of the library.

# Set the locale for sorting
export LC_ALL=C

cat << EndOfTextEndOfTextEndOfText
#########################################
# Syntax Coloring Map For IRremoteESP8266
#########################################

################################################
# WARNING: Do NOT edit this file directly.
#          It is generated by 'tools/mkkeywords'
#          e.g. tools/mkkeywords > keywords.txt
################################################

#######################################################
# The Arduino IDE requires the use of a tab separator
# between the name and identifier. Without this tab the
# keyword is not highlighted.
#
# Reference: https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5:-Library-specification#keywords
#######################################################

#######################################
# Datatypes & Classes (KEYWORD1)
#######################################

EndOfTextEndOfTextEndOfText

CLASSES=$(egrep -h \
          "^ *((enum|class|struct) [a-zA-Z0-9_]+|} [a-zA-Z0-9_]+_t;$)" src/*.h |
          sed 's/^ *//;s/enum class//;s/\;$//' | cut -d' ' -f2 | sed 's/:$//' |
          sort -u | grep -v "^__")
for i in ${CLASSES}; do
  echo -e "${i}\tKEYWORD1"
done | sort -du

cat << EndOfTextEndOfTextEndOfText

#######################################
# Methods and Functions (KEYWORD2)
#######################################

EndOfTextEndOfTextEndOfText
CTYPES="u?int(8|16|32|64)?(_t)?|void|bool|char|float|long|double|String|static"
OURTYPES="match_result_t|stdAc::state_t|decode_type_t"
METHODS=$(egrep -h "^[ ]{0,2}(${CTYPES}|${OURTYPES})\*? [^ ]*\(" src/*.cpp |
          sed 's/^  //' | cut -d' ' -f2 | sed 's/^\([^:]*::\| *\* *\)//' |
          cut -d'(' -f1 | sort -u | grep -v RAM_ATTR)
for i in ${METHODS}; do
  echo -e "${i}\tKEYWORD2"
done | sort -u

cat << EndOfTextEndOfTextEndOfText

#######################################
# Constants (LITERAL1)
#######################################

EndOfTextEndOfTextEndOfText
LITERALS=$(grep -h "^#define [A-Z]" src/*.cpp src/*.h |
           while read ignore define ignore; do
             echo ${define};
           done | sort -u |
           grep -v [\(\)] | grep -v ^_ | grep -v _\$ | grep -v VIRTUAL)
CONSTS=$(grep -h "^const " src/*.cpp src/*.h |
         sed -E 's/\[.*\] =.*//;s/ =.*//;s/^.* \*?k/k/';
         grep -h "^IRTEXT_CONST_" src/*.cpp src/*.h |
         sed -E 's/IRTEXT_CONST_\S+\(//;s/,.*//;s/\).*//')
ENUMS=$(cat src/*.h | while read a b; do
          if [[ ${a} == "};" ]]; then
            ENUM=0;
          fi;
          if [[ ${ENUM} -eq 1 ]]; then
            echo $a | sed 's/,//g';
          fi;
          if [[ ${a} == "enum" ]]; then
            ENUM=1;
          fi;
        done | grep -v "^//")
for i in ${LITERALS} ${CONSTS} ${ENUMS}; do
  echo -e "${i}\tLITERAL1"
done | sort -u
