1#!/usr/bin/env python
2
3import sys
4
5header_fname = sys.argv[1]
6output_fname = sys.argv[2]
7
8w = open(output_fname, 'w')
9
10w.write('''
11const char *
12wdns_rrtype_to_str(uint16_t rrtype)
13{
14    switch (rrtype) {
15''')
16
17for line in open(header_fname):
18    if 'WDNS_TYPE_' in line:
19        wdns_type = line.split()[1]
20        rrtype = wdns_type.replace('WDNS_TYPE_','',1).replace('_', '-')
21        w.write('\tcase %s: return ("%s");\n' % (wdns_type, rrtype))
22
23w.write('''    }
24
25    return (NULL);
26}
27''')
28
29w.write('''
30static struct u16str {
31    uint16_t u16;
32    const char *str;
33} rrtypes[] = {
34''')
35
36rrtypes = []
37for line in open(header_fname):
38    if 'WDNS_TYPE_' in line:
39        wdns_type = line.split()[1]
40        rrtype = wdns_type.replace('WDNS_TYPE_','',1).replace('_', '-')
41        rrtypes.append((wdns_type, rrtype))
42rrtypes.sort()
43for wdns_type, rrtype in rrtypes:
44    w.write('\t{ %s, "%s" },\n' % (wdns_type, rrtype))
45
46w.write('''};
47
48#define num_rrtypes (sizeof(rrtypes) / sizeof(struct u16str))
49
50static int
51cmp_u16str(const void *a, const void *b) {
52    struct u16str *u1 = (struct u16str *) a;
53    struct u16str *u2 = (struct u16str *) b;
54    return (strcasecmp(u1->str, u2->str));
55}
56
57static bool
58convert_generic_rrtype(const char *s, long int *val) {
59    char *endptr = NULL;
60
61    if (strlen(s) <= 4)
62        return (false);
63    if (strncasecmp(s, "TYPE", 4) != 0)
64        return (false);
65
66    s += 4; /* skip leading "TYPE" */
67
68    *val = strtol(s, &endptr, 10);
69    if (endptr != NULL && *endptr != '\\0')
70        return (false);
71    if (*val < 0 || *val > 65535)
72        return (false);
73
74    return (true);
75}
76
77uint16_t
78wdns_str_to_rrtype(const char *str) {
79    struct u16str key, *res;
80    key.str = str;
81    res = bsearch(&key, rrtypes, num_rrtypes, sizeof(struct u16str), cmp_u16str);
82    if (res != NULL) {
83        return (res->u16);
84    } else {
85        long int val = 0;
86        if (convert_generic_rrtype(str, &val))
87            return (val);
88    }
89    return (0);
90}
91''')
92
93w.close()
94