/**
 * Created by 212556710 on 10/13/16.
 */
var fs = require("fs");

var protractorConfigPath = "./node_modules/protractor/node_modules/webdriver-manager/config.json";
if (!fs.existsSync(protractorConfigPath)) {
    protractorConfigPath = "./node_modules/protractor/config.json";
}
var webdriverPath = "./node_modules/protractor/bin/webdriver-manager";
var packageJsonPath = "./package.json";
var gruntProtractorRunnerPath = "./node_modules/grunt-protractor-runner/node_modules";
require('dotenv').config();

fs.readFile(protractorConfigPath, "utf8", function (err, data) {
    if (err) console.log(err);
    if (process.env.chromedriver_ver != undefined)
        chromedriver_ver = process.env.chromedriver_ver;
    else chromedriver_ver = 2.39;
    var newVersion = '"chromedriver": ' + '"' + chromedriver_ver + '"'
    data = data.toString();
    data = data.replace(/"chromedriver": "[0-9].[0-9]+"/g, newVersion);
    fs.writeFile(protractorConfigPath, data, function (err) {
        if (err) console.log(err);
        fs.readFile(webdriverPath, "utf8", function (err, data) {
            if (err) console.log(err);
            data = data.toString();
            data = data.replace(/mac32/g, "mac64");
            fs.writeFile(webdriverPath, data, function (err) {
                if (err) console.log(err);
                fs.readFile(packageJsonPath, "utf8", function (err, data) {
                    if (err) console.log(err);
                    data = data.toString();
                    data = data.replace(/(grunt-protractor-runner\"\: \"\*\")/g, 'grunt-protractor-runner": "3.2.0"');
                    fs.writeFile(packageJsonPath, data, function (err) {
                        if (err) console.log(err);
                        var deleteFolderRecursive = function (path) {
                            if (fs.existsSync(path)) {
                                fs.readdirSync(path).forEach(function (file, index) {
                                    var curPath = path + "/" + file;
                                    if (fs.lstatSync(curPath).isDirectory()) { // recurse
                                        deleteFolderRecursive(curPath);
                                    } else { // delete file
                                        fs.unlinkSync(curPath);
                                    }
                                });
                                fs.rmdirSync(path);
                            }
                        };
                        deleteFolderRecursive(gruntProtractorRunnerPath);
                    });
                });

            });
        });
    });


});
