/*
 * Conversion functions for libuciconv
 *
 * SPDX-FileType: SOURCE
 * SPDX-FileCopyrightText: Michael Bäuerle
 * SPDX-License-Identifier: BSD-2-Clause
 */

#include <errno.h>
#include <stddef.h>
#include <stdio.h>
#include <string.h>

#include "libuciconv-0/iconv.h"


/* For every input octet a maximum of four UTF-8 output octets are created */
#define UCIC0_I_CLI_INBUF_SIZE   8192U
#define UCIC0_I_CLI_OUTBUF_SIZE  32768U


/* Data type for bool
 *
 * C90 provides no data type bool.
 * Semantics are value 0 for false and true otherwise.
 */
typedef unsigned char  ucic0_i_bool;


static char ucic0_i_cli_inbuf[UCIC0_I_CLI_INBUF_SIZE];
static char ucic0_i_cli_outbuf[UCIC0_I_CLI_OUTBUF_SIZE];

static ucic0_i_bool  ucic0_i_cli_omit_invalid    = 0;     /* For "-c" option */
static ucic0_i_bool  ucic0_i_cli_suppress_stderr = 0;     /* For "-s" option */
static const char   *ucic0_i_cli_from_encoding   = NULL;  /* For "-f" option */
static const char   *ucic0_i_cli_to_encoding     = NULL;  /* For "-t" option */
static const char   *ucic0_i_cli_pathname        = NULL;  /* For "file" */


/* ========================================================================== */
/*
 * Parse command line options.
 * Returns zero on success.
 */
static ucic0_i_bool ucic0_i_cli_parse_options(int argc, char **argv)
{
    if (5 > argc)
        goto error;

    {
        size_t       opt_num  = argc;
        ucic0_i_bool opt_from = 0;
        ucic0_i_bool opt_to   = 0;
        size_t       i        = 1;

        for ( ; opt_num > i; ++i)
        {
            if (opt_from)
            {
                opt_from                  = 0;
                ucic0_i_cli_from_encoding = argv[i];
                continue;
            }
            if (opt_to)
            {
                opt_to                  = 0;
                ucic0_i_cli_to_encoding = argv[i];
                continue;
            }

            if (!strcmp("-c", argv[i]))
                ucic0_i_cli_omit_invalid = 1;
            else if (!strcmp("-s", argv[i]))
                ucic0_i_cli_suppress_stderr = 1;
            else if (!strcmp("-f", argv[i]))
                opt_from = 1;
            else if (!strcmp("-t", argv[i]))
                opt_to = 1;
            else if (!strcmp("--", argv[i]))
            {
                /* POSIX conformant explicit option list termination */
                ++i;
                break;
            }
            else
                break;
        }

        /* First non-option is accepted as "file" operand */
        if (opt_num > i)
        {
            /* "-" must be treated as standard input */
            if (strcmp("-", argv[i]))
                ucic0_i_cli_pathname = argv[i];
        }
    }

    if ( (NULL == ucic0_i_cli_from_encoding) ||
         (NULL == ucic0_i_cli_to_encoding) )
        goto error;

    return 0;

error:
    fprintf(stderr, "Invalid options\n");
    return 1;
}


/* ========================================================================== */
/* Copy 'len' octets output buffer to standard output */
static void ucic0_i_cli_flush(size_t len)
{
    size_t i = 0;

    for ( ; len > i; ++i)
        fputc((unsigned char)ucic0_i_cli_outbuf[i], stdout);
}


/* ========================================================================== */
/*
 * Convert intput data.
 * Returns exit status for main().
 */
static int ucic0_i_cli_convert(FILE *instream)
{
    int flag = UCIC0_ICONV_IGNORE_NULL;

    while (1)
    {
        size_t outlen = UCIC0_I_CLI_OUTBUF_SIZE;
        size_t inlen  = fread(ucic0_i_cli_inbuf, 1, UCIC0_I_CLI_INBUF_SIZE,
                              instream);

        if (0 == inlen)
            break;

cont:
        errno = 0;
        {
            size_t in = inlen;
            size_t rv = ucic0_iconvstr(ucic0_i_cli_to_encoding,
                                       ucic0_i_cli_from_encoding,
                                       ucic0_i_cli_inbuf, &inlen,
                                       ucic0_i_cli_outbuf, &outlen,
                                       flag);

            if (UCIC0_I_CLI_OUTBUF_SIZE < outlen)
            {
                fprintf(stderr, "Invalid output data size (bug)\n");
                return 1;
            }
            if ((size_t)-1 == rv)
            {
                if (EBADF == errno)
                    fprintf(stderr, "Requested conversion not supported\n");
                else if (EILSEQ == errno)
                {
                    if (!ucic0_i_cli_suppress_stderr)
                        fprintf(stderr, "Invalid input octet\n");
                    if (0 == inlen)
                        fprintf(stderr, "No input data left (bug)\n");
                    else if (ucic0_i_cli_omit_invalid)
                    {
                        size_t converted = in - (--inlen);

                        ucic0_i_cli_flush(UCIC0_I_CLI_OUTBUF_SIZE - outlen);
                        outlen = UCIC0_I_CLI_OUTBUF_SIZE;
                        memmove(ucic0_i_cli_inbuf,
                                &ucic0_i_cli_inbuf[converted], inlen);
                        goto cont;
                    }
                }
                else
                    fprintf(stderr, "Unknown error (bug)\n");
                return 1;
            }
            if (0 != rv)
            {
                fprintf(stderr, "Conversion failed (bug)\n");
                return 1;
            }
        }
        ucic0_i_cli_flush(UCIC0_I_CLI_OUTBUF_SIZE - outlen);
    }

    return 0;
}


/* ========================================================================== */
int main(int argc, char **argv)
{
    FILE *instream = stdin;

    /* List available codeset descriptions */
    if (2 == argc && !strcmp("-l", argv[1]))
    {
        ucic0_print_codesets();
        return 0;
    }

    /* Setup conversion state */
    if (ucic0_i_cli_parse_options(argc, argv))
        return 1;

    /* Prepare input file stream */
    if (NULL != ucic0_i_cli_pathname)
    {
        instream = fopen(ucic0_i_cli_pathname, "rb");
        if (NULL == instream)
        {
            fprintf(stderr, "Failed to open input file\n");
            return 1;
        }
    }

    /* Execute conversion */
    return ucic0_i_cli_convert(instream);
}
