/* ========================================================================== */
/* Copyright (c) 2018-2021 Michael Baeuerle
 *
 * All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, and/or sell copies of the Software, and to permit persons
 * to whom the Software is furnished to do so, provided that the above
 * copyright notice(s) and this permission notice appear in all copies of
 * the Software and that both the above copyright notice(s) and this
 * permission notice appear in supporting documentation.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
 * OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
 * HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY
 * SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER
 * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
 * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
 * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *
 * Except as contained in this notice, the name of a copyright holder
 * shall not be used in advertising or otherwise to promote the sale, use
 * or other dealings in this Software without prior written authorization
 * of the copyright holder.
 *
 * SPDX-License-Identifier: ICU
 */

/*! Tell headers that they should be POSIX compliant */
#define _POSIX_C_SOURCE  200112L


/* ========================================================================== */
/* Include files */

/* POSIX */
#include <signal.h>
#include <unistd.h>

/* C99 */
#include <ctype.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/* Local */
#include "hfp_lexer.h"
#include "hfp_parser_external.h"
#include "package_name.h"


/* ========================================================================== */
/* Constants */

/*! Utility name suffix */
#define CL_USUFFIX  "-hfp"


/* ========================================================================== */
/* Global variables */

uint_least8_t cl_hfp_debugmode = 0;   /*!< Debugging enabled if true */
uint_least8_t cl_hfp_printhfn = 0;    /*!< Print field name if true */
static char sbuf[81];                 /*!< String buffer for debugging */


/* ========================================================================== */
/* Macros */

/*! Print debug message */
#define DEBUG(...) \
{ \
   snprintf(sbuf, 81, __VA_ARGS__); \
   debug(sbuf); \
}


/* ========================================================================== */
/*! \brief Print error message
 *
 * \param[in] msg  String (Error message)
 */

static void  print_error(char *msg)
{
   const char*  n = cl_hp_package_name();

   fprintf(stderr, "%s%s: %s\n", n, CL_USUFFIX, msg);
   free((void *) n);

   return;
}


/* ========================================================================== */
/*! \brief Print debug message */

static void debug(char *string)
{
   if (cl_hfp_debugmode)  fprintf(stderr, "Control: %s\n", string);

   return;
}


/* ========================================================================== */
/*! \brief Print program version information */

static void print_version(void)
{
   const char*  n = cl_hp_package_name();
   const char*  v = cl_hp_package_version();

   printf("%s%s %s\n", n, CL_USUFFIX, v);
   printf("%s\n", "Header parser for libcanlock (to parse header field)." );
   free((void *) n);

   return;
}


/* ========================================================================== */
/*! \brief Print help */

static void  print_help(void)
{
   const char*  n = cl_hp_package_name();

   printf("Usage: %s%s %s\n", n, CL_USUFFIX, "[options]\n"
          "Options:\n"
          "   -d               Enable debug mode\n"
          "   -h               Print this help message to stdout and exit\n"
          "                    (must be the only option)\n"
          "   -n               Prepend the data on stdout with the header\n"
          "                    field name (including the colon) and a SP\n"
          "                    (Space) delimiter\n"
          "   -v               Print version information to stdout and exit\n"
          "                    (must be the only option)\n"
          "(See manual page for details)"
   );
   free((void *) n);

   return;
}


/* ========================================================================== */
/*! \brief Error handler called by lexer and parser
 *
 * \param[in] msg  String (Error message)
 */

void cl_hfp_yyerror(char *msg)
{
   const char*  n = cl_hp_package_name();

   fprintf(stderr, "%s%s: %s\n", n, CL_USUFFIX, msg);
   free((void *) n);

   return;
}


/* ========================================================================== */
/*! \brief Main
 *
 * Parse command line and control compilation
 *
 * \return
 *    - 0: Success
 *    - 1: Error
 */

int main(int argc, char **argv)
{
   int rv = 0;                     /* 0: OK, 1: Error, 2: Abort but OK */
   int i;
   unsigned int err_opt = 0;       /* Error in options flag */

   /* Install signal handlers */
   if (SIG_ERR == signal(SIGPIPE, SIG_IGN))
   {
      print_error("Installation of signal handlers failed");
   }

   /* Process parameters */
   for (i = 1; i < argc; i++)
   {
      if (!strcmp(argv[i], "-d"))
      {
         /* Enable debugging */
         cl_hfp_debugmode = 1;
      }
      else if (!strcmp(argv[i], "-h") || !strcmp(argv[i], "--help"))
      {
         /* Print help and report success */
         print_help();
         rv = 2;
         break;
      }
      else if (!strcmp(argv[i], "-n"))
      {
         /* Print header field name */
         cl_hfp_printhfn = 1;
      }
      else if (!strcmp(argv[i], "-v") || !strcmp(argv[i], "--version"))
      {
         /* Print version information and report success */
         print_version();
         rv = 2;
         break;
      }
      else if ('-' == argv[i][0] && 1 != strlen(argv[i]))
      {
         /* Unknown option */
         err_opt = 1;
         rv = 1;
         break;
      }
   }
   /* Return value 2 indicate nothing more to do but no error */
   if (2 == rv)  rv = 0;
   else if (1 != rv)
   {
      DEBUG("Init");
      cl_hfp_yyinit();
      DEBUG("Start data processing");
      rv = cl_hfp_yyparse();
   }
   else if (err_opt)
   {
      print_error("Option error\nUse '-h' or look at the man page for help");
   }

   /* Check for error */
   if (!rv)
      DEBUG("Success")
   else
      DEBUG("Failed");

   exit(rv);
}


/*@}*/
/* EOF */
