// Poly-fill the String trim method.
if(!String.prototype.trim) {
    String.prototype.trim = function() {
        return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, "");
    };
}

function getObjects(text, token) {
    var i = text.indexOf(token);
    text = text.substr(i + token.length);
    i = text.indexOf("\r\n\r\n");
    return text.substr(0, i).replace(/..OBJ_D../g, " ").replace(/[ \t\r\n\\]+/g, " ").trim().split(' ');
}

function getProjectItems(text, objects) {
    // Microsoft's JavaScript implementation is not modern and doesn't have the
    // Array.map method.
    var rv = [];
    for(var i = 0, n = objects.length; i < n; ++i) {
        if(objects[i] == "cversion.obj") {
            // Skip this file.
            continue;
        }
        var source = getSource(text, objects[i]);
        rv.push('    <ClCompile Include="..\\sdk\\modules\\core\\dependencies\\openssl\\src' + source + '"/>\r\n');
    }
    rv.sort();
    return "  <ItemGroup>\r\n" + rv.join("") + "  </ItemGroup>\r\n";
}

function getSource(text, object) {
    var i = text.indexOf("$(OBJ_D)\\" + object + ":");
    if(i < 0) {
        throw object;
    }
    i = text.indexOf('\\', i + 11);
    if(i < 0) {
        throw object;
    }
    var j = text.indexOf('\r', i);
    if(j < 0) {
        throw object;
    }
    return text.substr(i, j - i);
}

// Create the file system object.
var ForReading = 1, ForWriting = 2, ForAppending = 8;
var fso = WScript.CreateObject("Scripting.FileSystemObject");

// Read the input make file.
var inputFile = fso.OpenTextFile("sdk\\modules\\core\\dependencies\\openssl\\src\\ms\\nt.mak", ForReading);
var text = inputFile.ReadAll();
inputFile.Close();

// Create the project items.
var objects1 = getObjects(text, "CRYPTOOBJ=");
var objects2 = getObjects(text, "SSLOBJ=");
var objects = objects1.concat(objects2);
var projectItems = getProjectItems(text, objects);

// Read the input project template file.
var inputFile = fso.OpenTextFile("openssl\\openssl.vcxproj.template", ForReading);
var text = inputFile.ReadAll();
inputFile.Close();

// Create the output project file.
var outputFile = fso.CreateTextFile("openssl\\openssl.vcxproj", true);
var i = text.indexOf("  <PropertyGroup");
outputFile.Write(text.substr(0, i));
outputFile.Write(projectItems);
outputFile.Write(text.substr(i));
outputFile.Close();

// Read the input project filters template file.
var inputFile = fso.OpenTextFile("openssl\\openssl.vcxproj.filters.template", ForReading);
var text = inputFile.ReadAll();
inputFile.Close();

// Create the output project filters file.
var outputFile = fso.CreateTextFile("openssl\\openssl.vcxproj.filters", true);
var i = text.indexOf("</Project");
outputFile.Write(text.substr(0, i));
outputFile.Write(projectItems);
outputFile.Write(text.substr(i));
outputFile.Close();
