#!/bin/bash

set -e

PHP_CMD=( php )
FLEX_CMD=( flex )
BISON_CMD=( bison )

OUT_DIR="generated/"

function bproto() {
    local input="$1"
    local name="$2"
    "${PHP_CMD[@]}" bproto_generator/bproto.php --input-file "${input}" --output-dir "${OUT_DIR}" --name "bproto_${name}"
}

function do_flex() {
    local input="$1"
    local name="$2"
    "${FLEX_CMD[@]}" -o "${OUT_DIR}/flex_${name}.c" --header-file="${OUT_DIR}/flex_${name}.h" "${input}"
}

function do_bison() {
    local input="$1"
    local name="$2"
    "${BISON_CMD[@]}" -d -o "${OUT_DIR}/bison_${name}.c" "${input}"
}

function do_lemon() {
    local input="$1"
    local name=$(basename "${input}")
    (
        cd generated &&
        rm -f "${name}" &&
        cp ../"${input}" "${name}" &&
        ../lemon/lemon "${name}"
    )
}

mkdir -p generated

bproto tests/bproto_test.bproto bproto_test
bproto protocol/msgproto.bproto msgproto
bproto protocol/addr.bproto addr
do_flex predicate/BPredicate.l BPredicate
do_bison predicate/BPredicate.y BPredicate
"${PHP_CMD[@]}" blog_generator/blog.php --input-file blog_channels.txt --output-dir "${OUT_DIR}"
do_lemon ncd/NCDConfigParser_parse.y
do_lemon ncd/NCDValueParser_parse.y
