aboutsummaryrefslogtreecommitdiff
path: root/cmd/service/help.c
blob: 30698d104983dedcb14a23c7c5df14e1d4c143f4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
/* SPDX-License-Identifier: ISC */
#include "servicecmd.h"

extern char *__progname;

static void pretty_print(const char *str, int padd, int len)
{
	int i, brk;
next:
	while (isspace(*str) && *str != '\n')
		++str;

	if (!(*str))
		return;

	if (*str == '\n') {
		fputc('\n', stdout);
		++str;
		len = padd;
		goto next;
	}

	for (i = 0, brk = 0; str[i]; ++i) {
		if (str[i] == '<' || str[i] == '[')
			++brk;
		if (str[i] == '>' || str[i] == ']')
			--brk;
		if (!brk && isspace(str[i]))
			break;
	}

	if ((len + i) < 80) {
		fwrite(str, 1, i, stdout);
		str += i;
		len += i;

		if ((len + 1) < 80) {
			fputc(' ', stdout);
			++len;
			goto next;
		}
	}

	printf("\n%*s", padd, "");
	len = padd;
	goto next;
}

static void print_cmd_usage(const char *cmd, const char *usage)
{
	int padd;

	padd = printf("Usage: %s %s ", __progname, cmd);

	if ((strlen(usage) + padd) < 80) {
		fputs(usage, stdout);
		return;
	}

	pretty_print(usage, padd, padd);
}

static int cmd_help(int argc, char **argv)
{
	const char *help;
	command_t *cmd;

	if (argc < 2)
		usage(EXIT_SUCCESS);

	if (argc > 2) {
		fprintf(stderr, "Too many arguments\n\n"
				"Usage: %s help <command>", __progname);
		return EXIT_FAILURE;
	}

	for (cmd = commands; cmd != NULL; cmd = cmd->next) {
		if (strcmp(cmd->cmd, argv[1]) != 0)
			continue;

		print_cmd_usage(cmd->cmd, cmd->usage);
		fputs("\n\n", stdout);

		help = cmd->l_desc ? cmd->l_desc : cmd->s_desc;

		if (islower(*help)) {
			fputc(toupper(*(help++)), stdout);
			pretty_print(help, 0, 1);
		} else {
			pretty_print(help, 0, 0);
		}

		fputc('\n', stdout);
		return EXIT_SUCCESS;
	}

	fprintf(stderr, "Unknown command '%s'\n\n"
			"Try `%s help' for a list of available commands\n",
			argv[1], __progname);
	return EXIT_FAILURE;
}

static command_t help = {
	.cmd = "help",
	.usage = "<command>",
	.s_desc = "print a help text for a command",
	.l_desc = "Print a help text for a specified command. If no command "
		"is specified, print a generic help text and a list of "
		"available commands.",
	.run_cmd = cmd_help,
};

REGISTER_COMMAND(help)