# -*- mode: python -*-

from __future__ import print_function
import sys
import re

header = open(sys.argv[1], "rb").read().decode("utf-8")
out_header = sys.argv[2]

"""
enum ln_error_t {
  LNE_CHECK_ERRNO = 1,         /* check errno for error description */
  LNE_NO_MEM = 2,              /* out of memory */
  LNE_NO_MANAGER_ADDRESS,      /* no -ln_manager HOST:PORT command line argument and not LN_MANAGER environment var */
  LNE_INVALID_MANAGER_ADDRESS, /* specified ln_manager address is not in format HOST_OR_IP:PORT_NUMBER */
  LNE_INVALID_HOSTNAME,        /* invalid hostname specified - has to be a hostname or an ip */
  LNE_UNKNOWN_HOSTNAME,        /* could not resolve hostname */
  LNE_HOST_WRONG_NET,          /* host resolved to wrong network family - should be IPv4 - AF_INET */

};
"""

match = re.search("enum ln_error_t {(.*?)};", header, re.S | re.M)
if not match:
    print("could not find enum ln_error in header!")
    sys.exit(-1)

consts = []
constvalue = 0
for m in match.group(1).strip().split("*/"):
    m = m.strip()
    if not m:
        continue

    constname, comment = m.split("/*", 1)
    comment = comment.strip()

    if "=" in constname:
        constname, constvalue = constname.split("=", 1)
        constname = constname.strip()
        constvalue = int(constvalue.rsplit(",", 1)[0])
    else:
        constname = constname.rsplit(",", 1)[0].strip()
        constvalue += 1
    consts.append((constvalue, constname, comment))
consts.sort()
errors_min = consts[0][0]
errors_max = consts[-1][0]

error_strings = []
index = 0
while index < errors_min:
    error_strings.append('\tNULL')
    index += 1
for v, n, c in consts:
    error_strings.append('\t"%s - %s"' % (n, c))
error_strings = ",\n".join(error_strings)

fp = open(out_header, "w")
fp.write("""
#ifndef LN_ERRORS_H
#define LN_ERRORS_H

int ln_errors_min = %d;
int ln_errors_max = %d;

const char* ln_errors[] = {
%s
};

#endif // LN_ERRORS_H
""" % (
        errors_min, errors_max, error_strings))
fp.close()
