package ganarchy.friendcode.util; import ganarchy.friendcode.FriendCode; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.util.Properties; import static org.apache.commons.lang3.SystemUtils.USER_HOME; import static org.apache.commons.lang3.SystemUtils.getEnvironmentVariable; /** * Config utils. */ public class ConfigUtil { /** * The message stored in the config. Could probably use some improvement. */ private static final String CONFIG_MESSAGE = "This is the friendcode config file." + " It's created when you open your world to a friend code."; /** * The (cached) global friendcode config dir. */ private static File confdir; /** * Creates and returns the global friendcode config dir. */ public static File getGlobalConfig() { if (confdir != null) { return confdir; } var configHome = getEnvironmentVariable("XDG_CONFIG_HOME", ""); if (!configHome.isEmpty()) { confdir = Path.of(configHome, "mc_friendcode").toFile(); } else { confdir = Path.of(USER_HOME, ".config", "mc_friendcode").toFile(); } confdir.mkdirs(); return confdir; } /** * Returns the path to the global friendcode config file. */ public static Path getGlobalConfigFilePath() { return getGlobalConfig().toPath().resolve("config.properties"); } /** * Retrieves the settings from the global config file and stores them in * the given object. * * @param properties Where to store the read config. * @return Whether reading was successful. */ public static boolean getSettings(Properties properties) { try { var inputStream = Files.newInputStream( getGlobalConfigFilePath() ); var reader = new InputStreamReader( inputStream, StandardCharsets.UTF_8 ); properties.load(reader); return true; } catch (IOException e) { return false; } } /** * Updates the global config file with the settings in the given object. * * @param properties The settings to add to the config. * @return Whether writing was successful. */ public static boolean updateSettings(Properties properties) { var prop = new Properties(); if (!getSettings(prop)) { FriendCode.LOGGER.warn( "Couldn't read global config." + " If it doesn't exist, it will be created." ); } prop.putAll(properties); try { var outputStream = Files.newOutputStream( getGlobalConfigFilePath() ); var writer = new OutputStreamWriter( outputStream, StandardCharsets.UTF_8 ); prop.store(writer, CONFIG_MESSAGE); return true; } catch (IOException e) { return false; } } }