1 /*
2  * Copyright (c) 2022 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  * http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 #include <signal.h>
16 #include <stdio.h>
17 #include <stdlib.h>
18 #include <termios.h>
19 
20 #include "begetctl.h"
21 #include "shell.h"
22 #include "shell_utils.h"
23 
24 static BShellHandle g_handle = NULL;
25 struct termios terminalState;
signalHandler(int signal)26 static void signalHandler(int signal)
27 {
28     demoExit();
29     exit(0);
30 }
31 
ShellInput(char * data,int32_t len)32 static int32_t ShellInput(char *data, int32_t len)
33 {
34     for (int32_t i = 0; i < len; i++) {
35         data[i] = getchar();
36     }
37     return len;
38 }
39 
GetShellHandle(void)40 BShellHandle GetShellHandle(void)
41 {
42     if (g_handle == NULL) {
43         BShellInfo info = {PARAM_SHELL_DEFAULT_PROMPT, ShellInput};
44         BShellEnvInit(&g_handle, &info);
45     }
46     return g_handle;
47 }
48 
49 #ifndef STARTUP_INIT_TEST
main(int argc,char * args[])50 int main(int argc, char *args[])
51 {
52     (void)signal(SIGINT, signalHandler);
53     (void)signal(SIGKILL, signalHandler);
54     if (tcgetattr(0, &terminalState)) {
55         return -1;
56     }
57     struct termios tio;
58     if (tcgetattr(0, &tio)) {
59         return -1;
60     }
61     tio.c_lflag &= ~(ECHO | ICANON | ISIG);
62     tio.c_cc[VTIME] = 0;
63     tio.c_cc[VMIN] = 1;
64     tcsetattr(0, TCSAFLUSH, &tio);
65 
66     BSH_LOGV("BShellEnvStart %d", argc);
67     do {
68         BShellHandle handle = GetShellHandle();
69         if (handle == NULL) {
70             printf("Failed to get shell handle \n");
71             return 0;
72         }
73         const ParamInfo *param = BShellEnvGetReservedParam(handle, PARAM_REVERESD_NAME_CURR_PARAMETER);
74         BSH_CHECK(param != NULL && param->type == PARAM_STRING, break, "Failed to get reversed param");
75         BShellEnvSetParam(handle, param->name, param->desc, param->type, (void *)"");
76         if (argc > 1) {
77             int ret = SetParamShellPrompt(handle, args[1]);
78             if (ret != 0) {
79                 break;
80             }
81         }
82         BShellParamCmdRegister(handle, 1);
83 #ifdef INIT_TEST
84         BShellCmdRegister(handle, 1);
85 #endif
86         BShellEnvStart(handle);
87         BShellEnvLoop(handle);
88     } while (0);
89     demoExit();
90     tcsetattr(0, TCSAFLUSH, &terminalState);
91     return 0;
92 }
93 #endif
94