#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <readline/readline.h>
#include <readline/history.h>
#include "moroz.h"
#include "config.h"
#include "ANTbin.h"
extern char ANT_NAME[64];
extern char ANT_NHOST[64];
char **parse_line(char *line) {
char **args = malloc(MAX_ARGS * sizeof(char *));
if (args == NULL) {
perror("ant_sh: malloc failed");
return NULL;
}
int i = 0;
char *token = strtok(line, " \t\n");
while (token != NULL && i < MAX_ARGS - 1) {
args[i++] = token;
token = strtok(NULL, " \t\n");
}
args[i] = NULL;
return args;
}
int main(void) {
char prompt[128];
if (!init()) {
fprintf(stderr, TXT_RED "Initialization failed. Exiting...\n" TXT_RESET);
return 1;
}
snprintf(prompt, sizeof(prompt), "\033[1;36m%s@%s -> \033[0m", ANT_NAME, ANT_NHOST);
while (1) {
char *line = readline(prompt);
if (line == NULL) {
fprintf(stderr, "\033[1;36m\nDosvidanie...\033[0m\n");
break;
}
if (*line == '\0') {
free(line);
continue;
}
add_history(line);
char **args = parse_line(line);
if (args == NULL || args[0] == NULL) {
if (args) free(args);
continue;
}
if (strcmp(args[0], "sys") == 0) {
if (args[1]) system(args[1]);
free(args);
free(line);
continue;
}
ANTbin_fn fn = ANTbin_find(args[0]);
if (fn) {
fn(args);
free(args);
free(line);
continue;
}
if (strcmp(args[0], "exit") == 0) {
fprintf(stderr, "\033[1;36mDosvidanie...\033[0m\n");
free(args);
free(line);
break;
}
pid_t pid = fork();
if (pid == 0) {
execvp(args[0], args);
perror("ant_sh");
_exit(127);
} else if (pid > 0) {
int status;
waitpid(pid, &status, 0);
}
free(args);
free(line);
}
return 0;
}