1#!/bin/bash
2set -e
3set -u
4
5rename() {
6  sed -r 's@(^|[^A-Za-z0-9_])'"$1"'([^A-Za-z0-9_]|$)@\1'"$2"'\2@g;'
7}
8
9apf_internal_function() {
10  rename "$1" "apf_internal_$1"
11}
12
13do_assemble() {
14  local -r RE_INCLUDE='^#include "([a-z_]+[.]h)"$'
15  local -r RE_UNDEF='^#undef ([_A-Za-z0-9]+)$'
16  local -r RE_DEFINE='^#define ([_A-Za-z0-9]+) (.*)$'
17
18  local line
19  while IFS='' read -r line; do
20    if [[ "${line}" =~ ${RE_INCLUDE} ]]; then
21      local include_name="${BASH_REMATCH[1]}"
22      case "${include_name}" in
23        apf_interpreter.h)
24          echo "#include \"${BASH_REMATCH[1]}\""
25          ;;
26        *)
27          echo "/* Begin include of ${include_name} */"
28          cat "${include_name}"
29          echo "/* End include of ${include_name} */"
30          ;;
31      esac
32    elif [[ "${line}" =~ ${RE_UNDEF} ]]; then
33      case "${BASH_REMATCH[1]}" in
34        bool|true|false) : ;;
35        *) echo "${line}" ;;
36      esac
37    elif [[ "${line}" =~ ${RE_DEFINE} ]]; then
38      case "${BASH_REMATCH[1]}" in
39        bool|true|false) : ;;
40        *) echo "${line}" ;;
41      esac
42    else
43      echo "${line}"
44    fi
45  done < apf_interpreter_source.c \
46  | sed -r 's@(^|[^:])//(.*)$@\1/*\2 */@;'\
47  | rename bool Boolean \
48  | rename true True \
49  | rename false False \
50  | apf_internal_function match_single_name \
51  | apf_internal_function match_names \
52  | apf_internal_function calc_csum \
53  | apf_internal_function csum_and_return_dscp \
54  | apf_internal_function do_transmit_buffer
55  # The above sed converts // comments into /* */ comments for c89,
56  # and converts bool/true/false into Boolean/True/False
57  # and converts non-static functions to have an apf_internal_ prefix
58}
59
60do_test() {
61  diff -q <(do_assemble) apf_interpreter.c
62}
63
64main() {
65  cd "${0%/*}"
66
67  local -r me="${0##*/}"
68  case "${me}" in
69    apf_interpreter_assemble.sh)
70      do_assemble > apf_interpreter.c
71      ;;
72    apf_assemble_test.sh)
73      do_test
74      ;;
75    *)
76      echo "Unknown $0" 1>&2
77      return 1
78      ;;
79  esac
80}
81
82main "$@"; exit
83