/****************************************************************************
 * apps/system/init/builtin.c
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.  The
 * ASF licenses this file to you 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.
 *
 ****************************************************************************/

/****************************************************************************
 * Included Files
 ****************************************************************************/

#include <sys/boardctl.h>

#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <spawn.h>
#include <sys/param.h>
#include <sys/wait.h>

#include <netutils/netinit.h>

#include "builtin.h"
#include "init.h"
#include "property.h"
#include "service.h"

/****************************************************************************
 * Private Types
 ****************************************************************************/

struct cmd_map_s
{
  FAR const char *cmd;
  uint8_t minargs;
  uint8_t maxargs;
  CODE int (*func)(FAR struct action_manager_s *, int, FAR char **);
};

/****************************************************************************
 * Private Function Prototypes
 ****************************************************************************/

static int cmd_trigger(FAR struct action_manager_s *am,
                       int argc, FAR char **argv);
static int cmd_exec_start(FAR struct action_manager_s *am,
                          int argc, FAR char **argv);
static int cmd_start(FAR struct action_manager_s *am,
                     int argc, FAR char **argv);
static int cmd_stop(FAR struct action_manager_s *am,
                    int argc, FAR char **argv);
#if CONFIG_SYSTEM_INIT_ACTION_EVENTS_MAX > 1
static int cmd_setprop(FAR struct action_manager_s *am,
                       int argc, FAR char **argv);
#endif
static int cmd_exec(FAR struct action_manager_s *am,
                    int argc, FAR char **argv);
static int cmd_class_start(FAR struct action_manager_s *am,
                           int argc, FAR char **argv);
static int cmd_class_stop(FAR struct action_manager_s *am,
                          int argc, FAR char **argv);
#ifdef CONFIG_BOARDCTL_BOOT_IMAGE
static int cmd_boot(FAR struct action_manager_s *am,
                    int argc, FAR char **argv);
#endif

#ifdef CONFIG_BOARDCTL_START_CPU
static int cmd_start_cpu(FAR struct action_manager_s *am,
                         int argc, FAR char **argv);
#endif
static int cmd_board_init(FAR struct action_manager_s *am,
                          int argc, FAR char **argv);
#ifdef CONFIG_NETUTILS_NETINIT
static int cmd_board_netinit(FAR struct action_manager_s *am,
                             int argc, FAR char **argv);
#endif
#ifdef CONFIG_BOARDCTL_FINALINIT
static int cmd_board_finalinit(FAR struct action_manager_s *am,
                               int argc, FAR char **argv);
#endif

/****************************************************************************
 * Private Data
 ****************************************************************************/

static const struct cmd_map_s g_builtin[] =
{
#ifdef CONFIG_BOARDCTL_BOOT_IMAGE
  {"boot", 1, 3, cmd_boot},
#endif
#ifdef CONFIG_BOARDCTL_START_CPU
  {"start_cpu", 1, 3, cmd_start_cpu},
#endif
  {"class_start", 2, 2, cmd_class_start},
  {"class_stop", 2, 2, cmd_class_stop},
  {"exec", 3, 99, cmd_exec},
  {"exec_start", 2, 2, cmd_exec_start},
#if CONFIG_SYSTEM_INIT_ACTION_EVENTS_MAX > 1
  {"setprop", 3, 3, cmd_setprop},
#endif
  {"start", 2, 2, cmd_start},
  {"stop", 2, 2, cmd_stop},
  {"trigger", 2, 2, cmd_trigger},
  {"board_init", 1, 1, cmd_board_init},
#ifdef CONFIG_NETUTILS_NETINIT
  {"board_netinit", 1, 1, cmd_board_netinit},
#endif
#ifdef CONFIG_BOARDCTL_FINALINIT
  {"board_finalinit", 1, 1, cmd_board_finalinit},
#endif
};

/****************************************************************************
 * Private Functions
 ****************************************************************************/

#ifdef CONFIG_BOARDCTL_BOOT_IMAGE
static int cmd_boot(FAR struct action_manager_s *am,
                    int argc, FAR char **argv)
{
  struct boardioc_boot_info_s info;

  UNUSED(am);
  memset(&info, 0, sizeof(info));

  if (argc > 1)
    {
      info.path = argv[1];
    }

  if (argc > 2)
    {
      info.header_size = strtoul(argv[2], NULL, 0);
    }

  boardctl(BOARDIOC_BOOT_IMAGE, (uintptr_t)&info);
  init_err("boot image '%s' %" PRIu32 "", info.path ? info.path : "",
           info.header_size);
  return -ENOENT;
}
#endif

#ifdef CONFIG_BOARDCTL_START_CPU
static int cmd_start_cpu(FAR struct action_manager_s *am,
                         int argc, FAR char **argv)
{
  int cpuid = 0;

  if (argc > 1)
    {
      cpuid = strtol(argv[1], NULL, 0);
    }

  init_info("start cpu %d", cpuid);
  return boardctl(BOARDIOC_START_CPU, cpuid);
}
#endif

static int cmd_class_start(FAR struct action_manager_s *am,
                           int argc, FAR char **argv)
{
  return init_service_start_by_class(am->sm, argv[1]);
}

static int cmd_class_stop(FAR struct action_manager_s *am,
                          int argc, FAR char **argv)
{
  return init_service_stop_by_class(am->sm, argv[1]);
}

static int cmd_exec_start(FAR struct action_manager_s *am,
                          int argc, FAR char **argv)
{
  FAR struct service_s *service;

  service = init_service_find_by_name(am->sm, argv[1]);
  if (!service)
    {
      init_err("no such service '%s'", argv[1]);
      return -EINVAL;
    }

  return init_service_start(service);
}

static int cmd_start(FAR struct action_manager_s *am,
                     int argc, FAR char **argv)
{
  int ret;

  ret = cmd_exec_start(am, argc, argv);
  return ret < 0 ? ret : 0;
}

static int cmd_stop(FAR struct action_manager_s *am,
                    int argc, FAR char **argv)
{
  FAR struct service_s *service;

  service = init_service_find_by_name(am->sm, argv[1]);
  if (!service)
    {
      init_err("no such service '%s'", argv[1]);
      return -EINVAL;
    }

  return init_service_stop(service);
}

#if CONFIG_SYSTEM_INIT_ACTION_EVENTS_MAX > 1
static int cmd_setprop(FAR struct action_manager_s *am, int argc,
                       FAR char **argv)
{
  return init_property_set(am->prop, argv[1], argv[2]);
}
#endif

static int cmd_trigger(FAR struct action_manager_s *am,
                       int argc, FAR char **argv)
{
  return init_action_add_event(am, argv[1]);
}

static int cmd_exec(FAR struct action_manager_s *am,
                    int argc, FAR char **argv)
{
  int i;

  for (i = 0; i < argc; i++)
    {
      if (!strcmp(argv[i], "--"))
        {
          i++;
          return init_builtin_run(am, argc - i, &argv[i]);
        }
    }

  return -EINVAL;
}

static int cmd_board_init(FAR struct action_manager_s *am,
                          int argc, FAR char **argv)
{
  return boardctl(BOARDIOC_INIT, 0);
}

#ifdef CONFIG_NETUTILS_NETINIT
static int cmd_board_netinit(FAR struct action_manager_s *am,
                             int argc, FAR char **argv)
{
  return netinit_bringup();
}
#endif

#ifdef CONFIG_BOARDCTL_FINALINIT
static int cmd_board_finalinit(FAR struct action_manager_s *am,
                               int argc, FAR char **argv)
{
  return boardctl(BOARDIOC_FINALINIT, 0);
}
#endif

/****************************************************************************
 * Public Functions
 ****************************************************************************/

/****************************************************************************
 * Name: init_builtin_run
 *
 * Description:
 *   Execute the builtin command of Init, builtin App, or NSH builtin.
 *
 * Input Parameters:
 *   am   - Instance of Action Manager.
 *   argc - Argument count.
 *   argv - A pointer to an array of string arguments. The end of the array
 *          is indicated with a NULL entry.
 *
 * Returned Value:
 *   Returns 0 (for Init builtin) or a PID(for builtin App or NSH builtin) on
 *   success; Returns the negative value of errno on failure.
 ****************************************************************************/

int init_builtin_run(FAR struct action_manager_s *am,
                     int argc, FAR char **argv)
{
  pid_t pid;
  size_t i;
  int ret;

  for (i = 0; i < nitems(g_builtin); i++)
    {
      if (!strcmp(g_builtin[i].cmd, argv[0]))
        {
          if (argc < g_builtin[i].minargs || argc > g_builtin[i].maxargs)
            {
              init_err("executing command '%s': invalid argument", argv[0]);
              init_dump_args(argc, argv);
              return -EINVAL;
            }

          init_info("executing command '%s'", argv[0]);
          return g_builtin[i].func(am, argc, argv);
        }
    }

  ret = posix_spawnp(&pid, argv[0], NULL, NULL, argv, NULL);
  if (ret != 0)
    {
#ifdef CONFIG_SYSTEM_SYSTEM
      char cmd[CONFIG_SYSTEM_INIT_RC_LINE_MAX];

      for (i = 0, cmd[i] = '\0'; i < argc; i++)
        {
          strlcat(cmd, argv[i], sizeof(cmd));
          if (i < argc - 1)
            {
              strcat(cmd, " ");
            }
        }

      init_debug("executing NSH command '%s'", cmd);
      ret = system(cmd);
      if (WIFEXITED(ret))
        {
          init_debug("NSH command '%s' exited %d", cmd, WEXITSTATUS(ret));
          return -WEXITSTATUS(ret);
        }
#endif

      init_err("executing command '%s': %d", argv[0], ret);
      init_dump_args(argc, argv);
      return -ret;
    }

  init_debug("executed command '%s' pid %d", argv[0], pid);
  return pid;
}