#!/bin/sh

# Copyright (c) 2023 by DomainTools LLC
# Copyright (c) 2015 by Farsight Security, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

if [ $# -ne 1 ] ; then
  echo "ERROR: Single argument expected"
  exit 1
fi

header_fname="$1"

## Build array of the variables of interest, WDNS_R_
## #define WDNS_R_NOERROR 0

defines=$(grep WDNS_R_ "$header_fname" | awk '{print $2}')

## Sort based on name
sorted=$(echo "$defines" | sort)

cat <<EOF
/*
 * Copyright (c) Farsight Security, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

const char *
wdns_rcode_to_str(uint16_t rcode)
{
   switch (rcode) {
EOF

for d in $defines ; do
	n=$(echo "$d" | sed -e 's/WDNS_[A-Z]*_//' -e 's/_/-/g')
	echo "   case $d: return (\"$n\");"
done

cat <<EOF
   }

   return (NULL);
}

static struct u16str {
    uint16_t u16;
    const char *str;
} rcodes[] = {
EOF

for l in $sorted ; do
	n=$(echo "$l" | sed -e 's/WDNS_[A-Z]*_//' -e 's/_/-/g')
	echo "   { $l, \"$n\" },"
done

cat <<EOF
};

#define num_rcodes (sizeof(rcodes) / sizeof(struct u16str))

static int
cmp_u16str(const void *a, const void *b) {
    struct u16str *u1 = (struct u16str *) a;
    struct u16str *u2 = (struct u16str *) b;
    return (strcasecmp(u1->str, u2->str));
}

wdns_res
wdns_str_to_rcode(const char *str, uint16_t *out) {
    struct u16str key, *res;
    key.str = str;
    res = bsearch(&key, rcodes, num_rcodes, sizeof(struct u16str), cmp_u16str);
    if (res != NULL) {
        *out = res->u16;
        return (wdns_res_success);
    }
    return (wdns_res_failure);
}
EOF
