/*
 * RESTHeart - the Web API for MongoDB
 * Copyright (C) SoftInstigate Srl
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 * 
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.restheart.utils;

import static com.sun.akuma.CLibrary.LIBC;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URL;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Enumeration;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Set;
import java.util.jar.Attributes;
import java.util.jar.Manifest;
import org.restheart.Configuration;
import org.restheart.ConfigurationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author Andrea Di Cesare {@literal <andrea@softinstigate.com>}
 */
public class FileUtils {

    private static final Logger LOGGER = LoggerFactory.getLogger(FileUtils.class);

    private static final Path DEFAULT_PID_DIR = new File("/var/run").toPath();
    private static final Path TMP_DIR = new File(System.getProperty("java.io.tmpdir")).toPath();

    public static Path getFileAbsolutePath(String path) {
        if (path == null) {
            return null;
        }

        return FileSystems.getDefault().getPath(path).toAbsolutePath();
    }

    public static int getFileAbsolutePathHash(Path path) {
        if (path == null) {
            return 0;
        }

        return Objects.hash(path.toString());
    }

    public static Configuration getConfiguration(String[] args) throws ConfigurationException {
        return getConfiguration(getConfigurationFilePath(args), false);
    }

    public static Configuration getConfiguration(String[] args, boolean silent) throws ConfigurationException {
        return getConfiguration(getConfigurationFilePath(args), silent);
    }

    public static Configuration getConfiguration(Path configurationFilePath, boolean silent) throws ConfigurationException {
        if (configurationFilePath != null) {
            return new Configuration(configurationFilePath, silent);
        } else {
            return new Configuration();
        }
    }

    public static Path getConfigurationFilePath(String[] args) {
        if (args != null) {
            for (String arg : args) {
                if (!arg.equals("--fork")) {
                    return getFileAbsolutePath(arg);
                }
            }
        }

        return null;
    }

    public static Path getTmpDirPath() {
        return TMP_DIR;
    }

    public static Path getPidFilePath(int configurationFileHash) {
        if (OSChecker.isWindows()) {
            return null;
        }

        if (Files.isWritable(DEFAULT_PID_DIR)) {
            return DEFAULT_PID_DIR.resolve("restheart-" + configurationFileHash + ".pid");
        } else {
            return TMP_DIR.resolve("restheart-" + configurationFileHash + ".pid");
        }
    }

    public static void createPidFile(Path pidFile) {
        if (OSChecker.isWindows()) {
            LOGGER.warn("this method is not supported on windows.");
            throw new IllegalStateException("createPidFile() is not supported on windows.");
        }

        try {
            try (FileWriter fw = new FileWriter(pidFile.toFile())) {

                fw.write(String.valueOf(LIBC.getpid()));
            }
        } catch (IOException e) {
            LOGGER.warn("error writing pid file", e);
        }
    }

    public static int getPidFromFile(Path pidFile) {
        try {
            try (BufferedReader br = new BufferedReader(new FileReader(pidFile.toFile()))) {
                String line = br.readLine();

                return Integer.parseInt(line);
            }
        } catch (FileNotFoundException fne) {
            LOGGER.debug("pid file not found", fne);
            return -1;
        } catch (IOException e) {
            LOGGER.debug("error reading the pid file", e);
            return -2;
        } catch (NumberFormatException e) {
            LOGGER.debug("unexpected content in pid file", e);
            return -3;
        }
    }

    public static Set<Entry<Object, Object>> findManifestInfo() {
        Set<Entry<Object, Object>> result = null;
        try {
            Enumeration<URL> resources = Thread.currentThread().getContextClassLoader()
                    .getResources("META-INF/MANIFEST.MF");
            while (resources.hasMoreElements()) {
                URL manifestUrl = resources.nextElement();
                Manifest manifest = new Manifest(manifestUrl.openStream());
                Attributes mainAttributes = manifest.getMainAttributes();
                String implementationTitle = mainAttributes.getValue("Implementation-Title");
                if (implementationTitle != null && implementationTitle.equals("Restheart")) {
                    result = mainAttributes.entrySet();
                    break;
                }
            }
        } catch (IOException e) {
            LOGGER.warn(e.getMessage());
        }
        return result;
    }

    private FileUtils() {
    }
}

@@ -72,17 +72,16 @@
 e Srl%0A *
- 
 %0A * This
@@ -330,25 +330,24 @@
  version.%0A *
- 
 %0A * This pro
@@ -590,17 +590,16 @@
 ails.%0A *
- 
 %0A * You 
@@ -3734,33 +3734,33 @@
 ot supported on 
-w
+W
 indows.%22);%0A     
@@ -3835,17 +3835,17 @@
 rted on 
-w
+W
 indows.%22
@@ -3857,35 +3857,16 @@
       %7D%0A
-%0A        try %7B%0A    
         
@@ -3922,20 +3922,16 @@
 e())) %7B%0A
-%0A   
         
@@ -3934,17 +3934,16 @@
         
- 
 fw.write
@@ -3975,30 +3975,16 @@
 id()));%0A
-            %7D%0A
         

Use try ... close statement