package com.atlassian.stash.internal.scm.git.protocol.ssh;

import com.atlassian.bitbucket.scm.git.GitUtils;
import com.google.common.collect.ImmutableSet;

import java.io.IOException;
import java.io.OutputStream;
import java.util.Set;


/**
 * Utilities for git over SSH.
 */
public abstract class GitSshUtils {

    public static final String COMMAND_RECEIVE_PACK = "receive-pack";
    public static final String COMMAND_UPLOAD_ARCHIVE = "upload-archive";
    public static final String COMMAND_UPLOAD_PACK = "upload-pack";

    public static final Set<String> SUPPORTED_COMMANDS =
            ImmutableSet.of(COMMAND_RECEIVE_PACK, COMMAND_UPLOAD_ARCHIVE, COMMAND_UPLOAD_PACK);

    private GitSshUtils() {
        throw new UnsupportedOperationException(getClass().getName() +
                " is a utility class and should not be instantiated");
    }

    public static void sendError(OutputStream stream, String summary, String detailedMessage) throws IOException {
        //Note: Under HTTP, git automatically adds a "fatal: remote error: " prefix before the summary as part
        //      of how the smart protocol interprets errors (see GitHttpUtils for more on that). For consistency,
        //      because git does not do that itself on SSH, we do it here. This keeps our error output consistent
        //      between HTTP and SSH, which simplifies learning/recognising error messages from Stash.
        String message = "fatal: remote error: " + summary + '\n' + GitUtils.wordWrap(detailedMessage) + '\n';

        stream.write(message.getBytes());
        stream.flush();
    }
}
