From 23f86cad954bae2f128d09cb14ea2d842bf2945c Mon Sep 17 00:00:00 2001
From: Andreas Grapentin <andreas@grapentin.org>
Date: Sun, 29 Nov 2020 07:51:20 +0100
Subject: [PATCH] src/config.c: added XDG_CONFIG_HOME support

---
 src/config.c | 38 +++++++++++++++++++++++++++++++-------
 src/mbsync.1 |  6 ++++--
 2 files changed, 35 insertions(+), 9 deletions(-)

diff --git a/src/config.c b/src/config.c
index e6d0ff4..841d28b 100644
--- a/src/config.c
+++ b/src/config.c
@@ -329,21 +329,45 @@ load_config( const char *where, int pseudo )
 	int cops, gcops, fn, i;
 	char path[_POSIX_PATH_MAX];
 	char buf[1024];
+	const char *config_home;
 
 	if (!where) {
 		assert( !pseudo );
-		nfsnprintf( path, sizeof(path), "%s/." EXE "rc", Home );
+		config_home = getenv("XDG_CONFIG_HOME");
+		if (config_home) {
+			nfsnprintf( path, sizeof(path), "%s/" EXE "/config", config_home );
+		} else {
+			nfsnprintf( path, sizeof(path), "%s/.config/" EXE "/config", Home );
+		}
 		cfile.file = path;
-	} else
-		cfile.file = where;
 
-	if (!pseudo)
 		info( "Reading configuration file %s\n", cfile.file );
+		cfile.fp = fopen( cfile.file, "r" );
 
-	if (!(cfile.fp = fopen( cfile.file, "r" ))) {
-		sys_error( "Cannot open config file '%s'", cfile.file );
-		return 1;
+		if (!cfile.fp) {
+			nfsnprintf( path, sizeof(path), "%s/." EXE "rc", Home );
+			cfile.file = path;
+
+			info( "Reading configuration file %s\n", cfile.file );
+			cfile.fp = fopen( cfile.file, "r" );
+		}
+
+		if (!cfile.fp) {
+			sys_error( "Cannot open user config file" );
+			return 1;
+		}
+	} else {
+		cfile.file = where;
+
+		if (!pseudo)
+			info( "Reading configuration file %s\n", cfile.file );
+
+		if (!(cfile.fp = fopen( cfile.file, "r" ))) {
+			sys_error( "Cannot open config file '%s'", cfile.file );
+			return 1;
+		}
 	}
+
 	buf[sizeof(buf) - 1] = 0;
 	cfile.buf = buf;
 	cfile.bufl = sizeof(buf) - 1;
diff --git a/src/mbsync.1 b/src/mbsync.1
index c2b79c4..4693724 100644
--- a/src/mbsync.1
+++ b/src/mbsync.1
@@ -47,7 +47,8 @@ Multiple replicas of each mailbox can be maintained.
 .TP
 \fB-c\fR, \fB--config\fR \fIfile\fR
 Read configuration from \fIfile\fR.
-By default, the configuration is read from ~/.mbsyncrc.
+By default, the configuration is read from $XDG_CONFIG_HOME/mbsync/config,
+or alternatively ~/.mbsyncrc.
 .TP
 \fB-a\fR, \fB--all\fR
 Select all configured channels. Any channel/group specifications on the command
@@ -803,8 +804,9 @@ There is no risk as long as the IMAP mailbox is accessed by only one client
 .
 .SH FILES
 .TP
+.B $XDG_CONFIG_HOME/mbsync/config
 .B ~/.mbsyncrc
-Default configuration file
+Default configuration files
 .TP
 .B ~/.mbsync/
 Directory containing synchronization state files
-- 
2.29.2

