#!/usr/bin/env python

# SPDX-FileCopyrightText: 2021 ret2libc <sirmy15@gmail.com>
# SPDX-License-Identifier: LGPL-3.0-only

import sys

TEMPLATE = '''/*
  This file was auto-generated by Meson from zip.h and zipint.h
*/

#include "zipint.h"

#define L ZIP_ET_LIBZIP
#define N ZIP_ET_NONE
#define S ZIP_ET_SYS
#define Z ZIP_ET_ZLIB

#define E ZIP_DETAIL_ET_ENTRY
#define G ZIP_DETAIL_ET_GLOBAL

const struct _zip_err_info _zip_err_str[] = {{
{zip_err_strs}
}};

const int _zip_err_str_count = sizeof(_zip_err_str)/sizeof(_zip_err_str[0]);

const struct _zip_err_info _zip_err_details[] = {{
{zip_err_details}
}};

const int _zip_err_details_count = sizeof(_zip_err_details)/sizeof(_zip_err_details[0]);
'''

zip_err_str_c = sys.argv[1]
zip_h = sys.argv[2]
zipint_h = sys.argv[3]

def getcomment(x):
    return x[x.index('/* ') + 3:x.index('*/')]

def def2errstr(x):
    comment = getcomment(x)
    val = comment.split(' ')[0]
    comment_str = comment.split(' ')[1]
    return f'{{{val}, "{comment_str}"}}'

def def2errdetail(x):
    comment = getcomment(x)
    val = comment.split(' ')[0]
    comment_str = comment.split(' ')[1]
    return f'{{{val}, "{comment_str}"}}'

defines = [l for l in open(zip_h, 'r').read().split('\n') if l.startswith('#define ZIP_ER')]
zip_err_strs = '\n'.join([def2errstr(x) + ',' for x in defines])

defines = [l for l in open(zipint_h, 'r').read().split('\n') if l.startswith('#define ZIP_ER_DETAIL')]
zip_err_details = '\n'.join([def2errdetail(x) + ',' for x in defines])

open(zip_err_str_c, 'w').write(TEMPLATE.format(zip_err_strs=zip_err_strs, zip_err_details=zip_err_details))
