package nu.studer.teamcity.buildscan.agent.servicemessage;

final class ServiceMessage {

    private static final String SERVICE_MESSAGE_START = "##teamcity[";
    private static final String SERVICE_MESSAGE_END = "]";

    private final String name;
    private final String argument;

    private ServiceMessage(String name, String argument) {
        this.name = name;
        this.argument = argument;
    }

    static ServiceMessage of(String name, String argument) {
        return new ServiceMessage(name, argument);
    }

    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append(SERVICE_MESSAGE_START);
        sb.append(name);
        sb.append(' ');
        sb.append('\'');
        sb.append(escape(argument));
        sb.append('\'');
        sb.append(SERVICE_MESSAGE_END);
        return sb.toString();
    }

    private String escape(String s) {
        StringBuilder sb = new StringBuilder();
        for (char c : s.toCharArray()) {
            sb.append(escape(c));
        }
        return sb.toString();
    }

    private String escape(final char c) {
        switch (c) {
            case '\n':
                return "n";
            case '\r':
                return "r";
            case '|':
                return "|";
            case '\'':
                return "\'";
            case '[':
                return "[";
            case ']':
                return "]";
            default:
                return c < 128 ? Character.toString(c) : String.format("0x%04x", (int) c);
        }
    }

}

@@ -1094,22 +1094,16 @@
  escape(
-final 
 char c) 
@@ -1099,24 +1099,62 @@
 pe(char c) %7B
+%0A        String escapeCharacter = %22%7C%22;
 %0A        swi
@@ -1208,16 +1208,34 @@
   return
+ escapeCharacter +
  %22n%22;%0A  
@@ -1277,16 +1277,34 @@
   return
+ escapeCharacter +
  %22r%22;%0A  
@@ -1345,16 +1345,34 @@
   return
+ escapeCharacter +
  %22%7C%22;%0A  
@@ -1414,16 +1414,34 @@
   return
+ escapeCharacter +
  %22%5C'%22;%0A 
@@ -1483,16 +1483,34 @@
   return
+ escapeCharacter +
  %22%5B%22;%0A  
@@ -1551,16 +1551,34 @@
   return
+ escapeCharacter +
  %22%5D%22;%0A  
@@ -1652,16 +1652,34 @@
 ing(c) :
+ escapeCharacter +
  String.

Fix message escaping to be the same as in the init script