From 008017ce1e1d6cf19f62451ac84b11520b80b748 Mon Sep 17 00:00:00 2001
From: Andre Noll <maan@tuebingen.mpg.de>
Date: Sun, 16 Jun 2019 13:46:45 +0200
Subject: [PATCH] Fall back to system-wide epigram directory.

If the per-user directory can not be opened, we currently print an
error message and exit. As pointed out by Adam Borowski, this is not
especially user-friendly.

This commit teaches tfortune to look in a second, system-wide location
in this case.  This location can be controlled with the --datadir
option of configure. The man page is updated accordingly.
---
 Makefile          | 2 ++
 config.mak.in     | 2 +-
 tfortune.c        | 7 +++++++
 tfortune.suite.m4 | 4 ++++
 4 files changed, 14 insertions(+), 1 deletion(-)

diff --git a/Makefile b/Makefile
index 5ad483b..d9f3197 100644
--- a/Makefile
+++ b/Makefile
@@ -99,6 +99,7 @@ version.c:
 index.html tfortune.suite: %: %.m4
 	$(call SAY, M4 $<)
 	$(M4) -D "AUTHOR=$(AUTHOR)" -D "COPYRIGHT_YEAR=$(COPYRIGHT_YEAR)" \
+		-D "DATADIR=$(datadir)" \
 		-D "PACKAGE=$(PACKAGE)" \
 		-D "SLOGAN=$(SLOGAN)" \
 		-D "EMAIL=$(EMAIL)" \
@@ -150,6 +151,7 @@ TF_CPPFLAGS += -DCC_VERSION='"$(cc_version)"'
 TF_CPPFLAGS += -DUNAME_RS='"$(uname_rs)"'
 TF_CPPFLAGS += -DLICENSE='"$(LICENSE)"'
 TF_CPPFLAGS += -DLICENSE_URL='"$(LICENSE_URL)"'
+TF_CPPFLAGS += -DDATADIR='"$(datadir)"'
 TF_CPPFLAGS += -I/usr/local/include
 
 TF_CFLAGS += -g
diff --git a/config.mak.in b/config.mak.in
index 829f420..b6468b4 100644
--- a/config.mak.in
+++ b/config.mak.in
@@ -3,9 +3,9 @@
 prefix := @prefix@
 exec_prefix := @exec_prefix@
 
-# These two use prefix and exec_prefix
 bindir := @bindir@
 datarootdir := @datarootdir@
+datadir := @datadir@
 
 FLEX := @FLEX@
 BISON := @BISON@
diff --git a/tfortune.c b/tfortune.c
index 02e54ea..e3eef04 100644
--- a/tfortune.c
+++ b/tfortune.c
@@ -302,9 +302,16 @@ static char *get_basedir(void)
 static char *get_epidir(void)
 {
 	char *basedir, *epidir;
+	struct stat s;
+
 	basedir = get_basedir();
 	xasprintf(&epidir, "%s/epigrams", basedir);
 	free(basedir);
+	if (!OPT_GIVEN(TFORTUNE, BASEDIR) && stat(epidir, &s) < 0) {
+		free(epidir);
+		epidir = xstrdup(DATADIR "/tfortunes/epigrams");
+		INFO_LOG("falling back to system-wide epidir %s\n", epidir);
+	}
 	return epidir;
 }
 
diff --git a/tfortune.suite.m4 b/tfortune.suite.m4
index ce0324a..dc8bae9 100644
--- a/tfortune.suite.m4
+++ b/tfortune.suite.m4
@@ -65,6 +65,10 @@ caption = Subcommands
 			Epigrams are expected in the "epigrams" subdirectory of the base
 			directory while tag expressions are expected to be stored below
 			"expressions".
+
+			If the option is not given, and the per-user epigram directory does
+			not exist, the system-wide default DATADIR() is tried. There is no
+			such fallback for tag expressions, though.
 		[/help]
 
 [subcommand compgen]
-- 
2.39.5