/*
 * Conversion functions for libjpiconv
 *
 * 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 "libjpiconv-0/iconv.h"
#include "libjpiconv-0/iconv_bool.h"


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


static char jpic0_i_cli_inbuf[JPIC0_I_CLI_INBUF_SIZE];
static char jpic0_i_cli_outbuf[JPIC0_I_CLI_OUTBUF_SIZE];

static jpic0_i_bool  jpic0_i_cli_omit_invalid    = 0;     /* For "-c" option */
static jpic0_i_bool  jpic0_i_cli_suppress_stderr = 0;     /* For "-s" option */
static const char   *jpic0_i_cli_from_encoding   = NULL;  /* For "-f" option */
static const char   *jpic0_i_cli_to_encoding     = NULL;  /* For "-t" option */
static const char   *jpic0_i_cli_pathname        = NULL;  /* For "file" */


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

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

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

            if (!strcmp("-c", argv[i]))
                jpic0_i_cli_omit_invalid = 1;
            else if (!strcmp("-s", argv[i]))
                jpic0_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]))
                jpic0_i_cli_pathname = argv[i];
        }
    }

    if ( (NULL == jpic0_i_cli_from_encoding) ||
         (NULL == jpic0_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 jpic0_i_cli_flush(size_t len)
{
    size_t i = 0;

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


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

    while (1)
    {
        size_t outlen = JPIC0_I_CLI_OUTBUF_SIZE;
        size_t inlen  = fread(jpic0_i_cli_inbuf, 1, JPIC0_I_CLI_INBUF_SIZE,
                              instream);

        if (0 == inlen)
            break;

cont:
        errno = 0;
        {
            size_t in = inlen;
            size_t rv = jpic0_iconvstr(jpic0_i_cli_to_encoding,
                                       jpic0_i_cli_from_encoding,
                                       jpic0_i_cli_inbuf, &inlen,
                                       jpic0_i_cli_outbuf, &outlen,
                                       flag);

            if (JPIC0_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 (!jpic0_i_cli_suppress_stderr)
                        fprintf(stderr, "Invalid input octet\n");
                    if (0 == inlen)
                        fprintf(stderr, "No input data left (bug)\n");
                    else if (jpic0_i_cli_omit_invalid)
                    {
                        size_t converted = in - (--inlen);

                        jpic0_i_cli_flush(JPIC0_I_CLI_OUTBUF_SIZE - outlen);
                        outlen = JPIC0_I_CLI_OUTBUF_SIZE;
                        memmove(jpic0_i_cli_inbuf,
                                &jpic0_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;
            }
        }
        jpic0_i_cli_flush(JPIC0_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]))
    {
        jpic0_print_codesets();
        return 0;
    }

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

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

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