package com.atlassian.bitbucket.mesh.process;

import com.atlassian.bitbucket.mesh.config.ApplicationConfig;
import com.atlassian.bitbucket.mesh.layout.StorageLayout;

import javax.annotation.Nonnull;
import java.nio.file.Path;

public class DefaultProcessConfigurer implements ProcessConfigurer {

    private final ApplicationConfig config;
    private final Path tempDir;
    private final String tempPath;

    public DefaultProcessConfigurer(ApplicationConfig config, StorageLayout layout) {
        this.config = config;
        tempDir = layout.getTempDir();
        tempPath = tempDir.toAbsolutePath().toString();
    }

    @Override
    public void configure(@Nonnull ProcessParameters<?> parameters) {
        //Try to encourage processes to write their temp files in BITBUCKET_HOME/tmp
        parameters.environmentPutIfAbsent("TMPDIR", tempPath);

        //If no explicit working directory has been set, rather than defaulting to the application's working directory,
        //default to BITBUCKET_HOME/tmp. Defaulting to the application's working directory has led to obscure support
        //cases due to inaccessible working directories.
        if (parameters.getWorkDir() == null) {
            parameters.setWorkDir(tempDir);
        }

        //Set execution and idle intervals, but only if no explicit value was set. That way, the configured values work
        //as defaults rather than fixed limits (some commands, like push/pull, may need different values)
        if (parameters.getExecutionInterval() == null) {
            parameters.setExecutionInterval(config.getDefaultExecutionTimeout());
        }
        if (parameters.getIdleInterval() == null) {
            parameters.setIdleInterval(config.getDefaultIdleTimeout());
        }
    }
}
