package com.atlassian.stash.internal.process;

import com.atlassian.bitbucket.auth.AuthenticationContext;
import com.atlassian.bitbucket.user.ApplicationUser;
import com.atlassian.utils.process.ExternalProcessConfigurer;
import com.atlassian.utils.process.ExternalProcessSettings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Nonnull;

/**
 * {@link ExternalProcessConfigurer} implementation that sets the standard cgi REMOTE_USER environment variable to the
 * context user's name, so it is passed on to any commit hook scripts registered by the user.
 *
 * @since 2.0
 */
@Component
public class RemoteUserExternalProcessConfigurer implements ExternalProcessConfigurer {

    private final AuthenticationContext authenticationContext;

    @Autowired
    public RemoteUserExternalProcessConfigurer(AuthenticationContext authenticationContext) {
        this.authenticationContext = authenticationContext;
    }

    @Override
    public void configure(@Nonnull ExternalProcessSettings settings) {
        ApplicationUser user = authenticationContext.getCurrentUser();
        if (user != null) {
            settings.getEnvironment().put("REMOTE_USER", user.getName());
        }
    }
}
