/*
 *
  ***** BEGIN LICENSE BLOCK *****
 
  Copyright (C) 2023 Olof Hagsand 

  This file is part of CLIXON.

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.

  Alternatively, the contents of this file may be used under the terms of
  the GNU General Public License Version 3 or later (the "GPL"),
  in which case the provisions of the GPL are applicable instead
  of those above. If you wish to allow use of your version of this file only
  under the terms of the GPL, and not to allow others to
  use your version of this file under the terms of Apache License version 2, 
  indicate your decision by deleting the provisions above and replace them with
  the  notice and other provisions required by the GPL. If you do not delete
  the provisions above, a recipient may use your version of this file under
  the terms of any one of the Apache License version 2 or the GPL.

  ***** END LICENSE BLOCK *****
 * 
 * Example cli pipe output functions.
 * @note Paths to bins, such as GREP_BIN, are detected in configure.ac
 * @note These functions are normally run in a forked sub-process as spawned in cligen_eval()
 * A developer should probably revise these functions, since they are primarily intended for testing
 * of the pipe functionality
 */

#ifdef HAVE_CONFIG_H
#include "clixon_config.h" /* generated by config & autoconf */
#endif

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <signal.h>
#include <errno.h>
#include <stdarg.h>
#include <time.h>
#include <ctype.h>

#include <unistd.h>
#include <dirent.h>
#include <syslog.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/wait.h>
#include <sys/param.h>
#include <sys/mount.h>
#include <pwd.h>

/* cligen */
#include <cligen/cligen.h>

/* clixon */
#include <clixon/clixon.h>

#include "clixon_cli_api.h"

/* General-purpose pipe output function
 *
 * @param[in]  h      Clixon handle
 * @param[in]  cmd    Command to exec
 * @param[in]  option Option to command (or NULL)
 * @param[in]  value  Command argument value (or NULL)
 */
int
pipe_arg_fn(clixon_handle h,
            char         *cmd,
            char         *option,
            char         *value)
{
    int          retval = -1;
    struct stat  fstat;
    char       **argv = NULL;
    int          i;

    if (cmd == NULL || strlen(cmd) == 0){
        clixon_err(OE_PLUGIN, EINVAL, "cmd '%s' NULL or empty", cmd);
        goto done;
    }
    if (stat(cmd, &fstat) < 0) {
        clixon_err(OE_UNIX, errno, "stat(%s)", cmd);
        goto done;
    }
    if (!S_ISREG(fstat.st_mode)){
        clixon_err(OE_UNIX, errno, "%s is not a regular file", cmd);
        goto done;
    }
    if ((argv = calloc(4, sizeof(char *))) == NULL){
        clixon_err(OE_UNIX, errno, "calloc");
        goto done;
    }
    i = 0;
    argv[i++] = cmd;
    argv[i++] = option;
    argv[i++] = value;
    argv[i++] = NULL;
    retval = execv(cmd, argv);
 done:
    if (argv)
        free(argv);
    return retval;
}

/* Grep pipe output function
 *
 * @param[in]  h     Clixon handle
 * @param[in]  cvv   Vector of cli string and instantiated variables 
 * @param[in]  argv  String vector of options. Format: <option> <value>
 * @note  Any vertical bar (|] in the patterns field is quoted for OR function
 */
int
pipe_grep_fn(clixon_handle h,
             cvec         *cvv,
             cvec         *argv)
{
    int     retval = -1;
    char   *pattern = NULL;
    cg_var *cv;
    char   *str;
    char   *option = NULL;
    char   *argname = NULL;
    cbuf   *cb = NULL;
    int     i;
    char    c;

    if (cvec_len(argv) != 2){
        clixon_err(OE_PLUGIN, EINVAL, "Received %d arguments. Expected: <option> <argname>", cvec_len(argv));
        goto done;
    }
    if ((cv = cvec_i(argv, 0)) != NULL &&
        (str = cv_string_get(cv)) != NULL &&
        strlen(str))
        option = str;
    if ((cv = cvec_i(argv, 1)) != NULL &&
        (str = cv_string_get(cv)) != NULL &&
        strlen(str))
        argname = str;
    if ((cb = cbuf_new()) == NULL){
        clixon_err(OE_UNIX, errno, "cbuf_new");
        goto done;
    }
    if (argname && strlen(argname)){
        if ((cv = cvec_find_var(cvv, argname)) != NULL &&
            (str = cv_string_get(cv)) != NULL &&
            strlen(str))
            pattern = str;
    }
    /* quote | in pattern into cbuf */
    for (i=0; i<strlen(pattern); i++){
        c = pattern[i];
        if (c == '|')
            cprintf(cb, "\\|");
        else
            cprintf(cb, "%c", c);
    }
    retval = pipe_arg_fn(h, GREP_BIN, option, cbuf_get(cb));
 done:
    if (cb)
        cbuf_free(cb);
    return retval;
}

/*! wc pipe output function
 *
 * @param[in]  h     Clixon handle
 * @param[in]  cvv   Vector of cli string and instantiated variables 
 * @param[in]  argv  String vector of options. Format: <option> <value>
 * @retval     0     OK
 * @retval    -1     Error
 */
int
pipe_wc_fn(clixon_handle h,
           cvec         *cvv,
           cvec         *argv)
{
    int     retval = -1;
    cg_var *cv;
    char   *str;
    char   *option = NULL;

    if (cvec_len(argv) != 1){
        clixon_err(OE_PLUGIN, EINVAL, "Received %d arguments. Expected: <NUM>", cvec_len(argv));
        goto done;
    }
    if ((cv = cvec_i(argv, 0)) != NULL &&
        (str = cv_string_get(cv)) != NULL &&
        strlen(str))
        option = str;
    retval = pipe_arg_fn(h, WC_BIN, option, NULL);
 done:
    return retval;
}

/*! wc pipe output function
 *
 * @param[in]  h     Clixon handle
 * @param[in]  cvv   Vector of cli string and instantiated variables 
 * @param[in]  argv  String vector of options. Format: <option> <value>
 * @retval     0     OK
 * @retval    -1     Error
 */
int
pipe_tail_fn(clixon_handle h,
             cvec         *cvv,
             cvec         *argv)
{
    int     retval = -1;
    char   *value = NULL;
    cg_var *cv;
    char   *str;
    char   *option = NULL;
    char   *argname = NULL;

    if (cvec_len(argv) != 2){
        clixon_err(OE_PLUGIN, EINVAL, "Received %d arguments. Expected: <option> <argname>", cvec_len(argv));
        goto done;
    }
    if ((cv = cvec_i(argv, 0)) != NULL &&
        (str = cv_string_get(cv)) != NULL &&
        strlen(str))
        option = str;
    if ((cv = cvec_i(argv, 1)) != NULL &&
        (str = cv_string_get(cv)) != NULL &&
        strlen(str))
        argname = str;
    if (argname && strlen(argname)){
        if ((cv = cvec_find_var(cvv, argname)) != NULL &&
            (str = cv_string_get(cv)) != NULL &&
            strlen(str))
            value = str;
    }
    return pipe_arg_fn(h, TAIL_BIN, option, value);
 done:
    return retval;
}

/*! Output pipe translate from xml to other format: json,text,
 *
 * @param[in]  h     Clixon handle
 * @param[in]  cvv   Vector of cli string and instantiated variables 
 * @param[in]  argv  String vector of show options, format:
 *   <format>        "text"|"xml"|"json"|"cli"|"netconf" (see format_enum), default: xml
 *   <pretty>        true|false: pretty-print or not
 *   <prepend>       CLI prefix: prepend before cli syntax output
 * @retval     0     OK
 * @retval    -1     Error
 * @see cli_show_auto_devs
 */
int
pipe_showas_fn(clixon_handle h,
               cvec         *cvv,
               cvec         *argv)
{
    int              retval = -1;
    cxobj           *xt = NULL;
    int              argc = 0;
    enum format_enum format = FORMAT_XML;
    yang_stmt       *yspec;
    int              pretty = 1;
    char            *prepend = NULL;
    int              ret;
    cxobj           *xerr = NULL;

    if (cvec_len(argv) < 1 || cvec_len(argv) > 3){
        clixon_err(OE_PLUGIN, EINVAL, "Received %d arguments. Expected:: <format> [<pretty> [<prepend>]]", cvec_len(argv));
        goto done;
    }
    if (cvec_len(argv) > argc){
        if (cli_show_option_format(h, argv, argc++, &format) < 0)
            goto done;
    }
    if (cvec_len(argv) > argc){
        if (cli_show_option_bool(argv, argc++, &pretty) < 0)
            goto done;
    }
    if (cvec_len(argv) > argc){
        prepend = cv_string_get(cvec_i(argv, argc++));
    }
    yspec = clicon_dbspec_yang(h);
    /* Bind module with mtpoints requires h, but parse functions font have h */
    if (clixon_xml_parse_file(stdin, YB_NONE, yspec, &xt, NULL) < 0)
        goto done;
    switch (format){
    case FORMAT_CLI:
    case FORMAT_TEXT:
    case FORMAT_JSON:
        /* Requires binding. Note binding over mountpoints can cause rpc: extra latency */
        if ((ret = xml_bind_yang(h, xt, YB_MODULE, yspec, &xerr)) < 0)
            goto done;
        if (ret == 0){
            clixon_err_netconf(h, OE_NETCONF, 0, xerr, "Parse top file");
            goto done;
        }
        break;
    default:
        break;
    }
    switch (format){
    case FORMAT_XML:
        if (clixon_xml2file(stdout, xt, 0, pretty, NULL, cligen_output, 1, 0) < 0)
            goto done;
        break;
    case FORMAT_JSON:
        if (clixon_json2file(stdout, xt, pretty, cligen_output, 1, 0) < 0)
            goto done;
        break;
    case FORMAT_TEXT:
        if (clixon_text2file(stdout, xt, 0, cligen_output, 1, 1) < 0)
            goto done;
        break;
    case FORMAT_CLI:
        if (clixon_cli2file(h, stdout, xt, prepend, cligen_output, 1) < 0) /* cli syntax */
            goto done;
        break;
    default:
        break;
    }
    retval = 0;
 done:
    if (xerr)
        xml_free(xerr);
    if (xt)
        xml_free(xt);
    return retval;
}

/*! pipe function: save to file
 *
 * @param[in]  h     Clixon handle
 * @param[in]  cvv   Vector of cli string and instantiated variables 
 * @param[in]  argv  String vector of options. Format: <argname>
 * @retval     0     OK
 * @retval    -1     Error
 */
int
pipe_save_file(clixon_handle h,
               cvec         *cvv,
               cvec         *argv)
{
    int     retval = -1;
    cg_var *cv;
    char   *str;
    char   *argname = NULL;
    char   *filename = NULL;
    int     fd;

    if (cvec_len(argv) != 1){
        clixon_err(OE_PLUGIN, EINVAL, "Received %d arguments. Expected: <argname>", cvec_len(argv));
        goto done;
    }
    if ((cv = cvec_i(argv, 0)) != NULL &&
        (str = cv_string_get(cv)) != NULL &&
        strlen(str)){
        argname = str;
    }
    if (argname && strlen(argname)){
        if ((cv = cvec_find_var(cvv, argname)) != NULL &&
            (str = cv_string_get(cv)) != NULL &&
            strlen(str))
            filename = str;
    }
    if (filename){
        if ((fd = creat(filename, S_IRUSR | S_IWUSR)) < 0){
            clixon_err(OE_CFG, errno, "creat(%s)", filename);
            goto done;
        }
        close(1);
        if (dup2(fd, STDOUT_FILENO) < 0){
            clixon_err(OE_UNIX, errno, "dup2(STDOUT)");
            return -1;
        }
        return pipe_arg_fn(h, CAT_BIN, NULL, NULL);
    }
 done:
    return retval;
}

/*! Test cli callback calls cligen_output with output lines as given by function arguments
 *
 * Only for test or debugging to generate output to eg cligen_output scrolling
 * Example:
 * a, printlines_fn("line1 abc", "line2 def");
 */
int
output_fn(cligen_handle handle,
          cvec         *cvv,
          cvec         *argv)
{
    cg_var *cv;

    cv = NULL;
    while ((cv = cvec_each(argv, cv)) != NULL){
        cligen_output(stdout, "%s\n", cv_string_get(cv));
    }
    return 0;
}
