1 /*
2  * Copyright (C) 2014, Lanedo <martyn@lanedo.com>
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software
16  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
17  * 02110-1301, USA.
18  */
19 
20 #include "config.h"
21 
22 #include <unistd.h>
23 #include <errno.h>
24 
25 #include <glib/gi18n.h>
26 
27 #include "tracker-help.h"
28 
29 static void
setup_man_path(void)30 setup_man_path (void)
31 {
32 	GString *new_path = g_string_new ("");
33 	const char *old_path = g_getenv ("MANPATH");
34 
35 	/* We should always put ':' after our path. If there is no
36 	 * old_path, the ':' at the end will let 'man' to try
37 	 * system-wide paths after ours to find the manual page. If
38 	 * there is old_path, we need ':' as delimiter. */
39 	g_string_append (new_path, MANDIR);
40 	g_string_append_c (new_path, ':');
41 
42 	if (old_path) {
43 		g_string_append (new_path, old_path);
44 	}
45 
46 	g_setenv ("MANPATH", new_path->str, TRUE);
47 
48 	g_string_free (new_path, TRUE);
49 }
50 
51 static int
exec_man_man(const char * path,const char * page)52 exec_man_man (const char *path, const char *page)
53 {
54 	if (!path) {
55 		path = "man";
56 	}
57 
58 	execlp (path, "man", page, (char *) NULL);
59 	g_warning(_("failed to exec “%s”: %s"), path, strerror (errno));
60 
61 	return -1;
62 }
63 
64 static int
exec_man_cmd(const char * cmd,const char * page)65 exec_man_cmd (const char *cmd, const char *page)
66 {
67 	gchar *shell_cmd;
68 
69 	shell_cmd = g_strdup_printf ("%s %s", cmd, page);
70 	execl ("/bin/sh", "sh", "-c", shell_cmd, (char *) NULL);
71 	g_warning (_("failed to exec “%s”: %s"), cmd, strerror (errno));
72 	g_free (shell_cmd);
73 
74 	return -1;
75 }
76 
77 static char *
cmd_to_page(const char * cmd)78 cmd_to_page (const char *cmd)
79 {
80 	if (!cmd) {
81 		return g_strdup ("tracker");
82 	} else if (g_str_has_prefix (cmd, "tracker")) {
83 		return g_strdup (cmd);
84 	} else {
85 		return g_strdup_printf ("tracker-%s", cmd);
86 	}
87 }
88 
89 int
tracker_help_show_man_page(const char * cmd)90 tracker_help_show_man_page (const char *cmd)
91 {
92 	const char *page = cmd_to_page (cmd);
93 
94 	setup_man_path ();
95 
96 	if (0) {
97 		exec_man_cmd ("man", page);
98 	}
99 
100 	return exec_man_man ("man", page);
101 }
102 
103