#!/bin/sh

if test -z "$3"; then
  echo "Usage:   $0 <enum> <prefix> <header>"
  echo "Example: $0 FooResult FOO foo_types.h"
  exit 1
fi

ENUM=$1
PREFIX=$2
HEADER=$3


cat << EOF
/*
 * Generated by mkresult.sh
 */

#include <direct/result.h>

static const char *${ENUM}__strings[${PREFIX}__RESULT_END - ${PREFIX}__RESULT_BASE];

static DirectResultType ${ENUM}__type = {
     0, 0,
     ${PREFIX}__RESULT_BASE,
     ${ENUM}__strings,
     sizeof(${ENUM}__strings) / sizeof(char*)
};

void
${ENUM}__init(void)
{
     ${ENUM}__strings[0] = "${ENUM}";

EOF

(
    while read line; do
        (echo "$line" | egrep -q "^${PREFIX}__RESULT_BASE += +D_RESULT_TYPE_CODE_BASE") && break
    done

    while read line; do
        (echo "$line" | egrep -q "^ *${PREFIX}__RESULT_END") && break

        test -z "$line" || echo "$line" | perl -p -e "s/^\\s*(${PREFIX}_[\\w_]+)\\s*,?\\s+\\/\\*\\s*(.*[^ ])\\s*\\*\\//     ${ENUM}__strings[D_RESULT_INDEX(\\1)] = \\\"\\2\\\";/"
    done
) < ${HEADER}

cat << EOF

     DirectResultTypeRegister( &${ENUM}__type );
}

void
${ENUM}__deinit(void)
{
     DirectResultTypeUnregister( &${ENUM}__type );
}

EOF

