From 5201a07a63fbce3f7e072034efd150929edf711e Mon Sep 17 00:00:00 2001
From: Zack Middleton <zack@cloemail.com>
Date: Fri, 10 Jan 2025 02:41:21 -0600
Subject: [PATCH] Change Unix homepath to support XDG_DATA_HOME

Existing installs continue to use ~/.q3a but new installs use
~/.local/share/q3a.

~/.local/share/q3a is always used if it exists. Otherwise it will use
~/.q3a if it exists or create ~/.local/share/q3a. This prevents
switching to ~/.q3a if another client creates it later.

This supports '+set com_homepath ".foo"' to override paths to ~/.foo and
~/.local/share/foo.
---
 code/sys/sys_unix.c | 59 ++++++++++++++++++++++++++-------------------
 1 file changed, 34 insertions(+), 25 deletions(-)

diff --git a/code/sys/sys_unix.c b/code/sys/sys_unix.c
index 07de650068..d1ba21a645 100644
--- a/code/sys/sys_unix.c
+++ b/code/sys/sys_unix.c
@@ -79,40 +79,49 @@ char *Sys_DefaultHomePath(void)
 				Q_strcat(homePath, sizeof(homePath), HOMEPATH_NAME_MACOSX);
 		}
 #else
+		char origPath[ MAX_OSPATH ] = { 0 };
+
 		if( ( p = getenv( "FLATPAK_ID" ) ) != NULL && *p != '\0' )
 		{
-			if( ( p = getenv( "XDG_DATA_HOME" ) ) != NULL && *p != '\0' )
-			{
-				Com_sprintf(homePath, sizeof(homePath), "%s%c", p, PATH_SEP);
-			}
-			else if( ( p = getenv( "HOME" ) ) != NULL && *p != '\0' )
-			{
-				Com_sprintf(homePath, sizeof(homePath), "%s%c.local%cshare%c", p, PATH_SEP, PATH_SEP, PATH_SEP);
-			}
-
-			if( *homePath )
-			{
-				char *dir;
-
-				if(com_homepath->string[0])
-					dir = com_homepath->string;
-				else
-					dir = HOMEPATH_NAME_UNIX;
-
-				if(dir[0] == '.' && dir[1] != '\0')
-					dir++;
-
-				Q_strcat(homePath, sizeof(homePath), dir);
-			}
+			// don't use original homepath in Flatpak
 		}
 		else if( ( p = getenv( "HOME" ) ) != NULL )
+		{
+			Com_sprintf(origPath, sizeof(origPath), "%s%c", p, PATH_SEP);
+
+			if(com_homepath->string[0])
+				Q_strcat(origPath, sizeof(origPath), com_homepath->string);
+			else
+				Q_strcat(origPath, sizeof(origPath), HOMEPATH_NAME_UNIX);
+		}
+
+		if( ( p = getenv( "XDG_DATA_HOME" ) ) != NULL && *p != '\0' )
 		{
 			Com_sprintf(homePath, sizeof(homePath), "%s%c", p, PATH_SEP);
+		}
+		else if( ( p = getenv( "HOME" ) ) != NULL && *p != '\0' )
+		{
+			Com_sprintf(homePath, sizeof(homePath), "%s%c.local%cshare%c", p, PATH_SEP, PATH_SEP, PATH_SEP);
+		}
+
+		if( *homePath )
+		{
+			char *dir;
 
 			if(com_homepath->string[0])
-				Q_strcat(homePath, sizeof(homePath), com_homepath->string);
+				dir = com_homepath->string;
 			else
-				Q_strcat(homePath, sizeof(homePath), HOMEPATH_NAME_UNIX);
+				dir = HOMEPATH_NAME_UNIX;
+
+			if(dir[0] == '.' && dir[1] != '\0')
+				dir++;
+
+			Q_strcat(homePath, sizeof(homePath), dir);
+		}
+
+		if( *homePath == '\0' || ( *origPath != '\0' && access(origPath, F_OK) == 0 && access(homePath, F_OK) < 0 ) )
+		{
+			Q_strncpyz(homePath, origPath, sizeof(homePath));
 		}
 #endif
 	}