

var source_file,java_config_path,L,key,value,FL
var IP_REG = new RegExp(/((?:(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))\.){3}(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d))))/g);

process.argv.forEach(function (val, index, array) {
	if(index == 2){
		source_file = val;
	}else{
		java_config_path = val;
	}
});

console.log("本地配置文件:%s",source_file)
console.log("项目配置文件:%s",java_config_path)

function getNowFormatDate() {
    var date = new Date();
    var seperator1 = "-";
    var seperator2 = ":";
    var month = date.getMonth() + 1;
    var strDate = date.getDate();
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
    }
    var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
            + " " + date.getHours() + seperator2 + date.getMinutes()
            + seperator2 + date.getSeconds();
    return currentdate;
} 

var list_source_file_keys = {},diff_list=[],value_of_diff_change;
var java_config_data,java_config_data_lines;
var fs=require("fs");
var path = require('path');
var list_source_file_data = fs.readFileSync(source_file,'utf-8');
var lines = list_source_file_data.split("\n")
for (var i = 0; i < lines.length; ++i) {
		L = lines[i].split("=")
		key = L[0]
		value = L[1]
		FL = L[0].replace(/\s/g,"");
		if( FL[0] != "#" && FL.length != 0){
			list_source_file_keys[L[0]] = L[1];
		}
}

fs.readdir(java_config_path,function(err,files){
	var count = files.length;
	files.forEach(function(filename){
		if(filename.indexOf(".properties") != -1){
			var java_config_data = fs.readFileSync(path.join(java_config_path,filename),'utf-8');
			var java_config_data_lines = java_config_data.split("\n")
			for (var i = 0; i < java_config_data_lines.length; ++i) {
				L = java_config_data_lines[i].split("=")
				key = L[0]
				value = L[1]
				FL = L[0].replace(/\s/g,"");
				if( FL[0] != "#" && FL.length != 0){
					if(typeof list_source_file_keys[L[0]] == "undefined"){
						console.log("Warning!!!: \"%s\"\t",L[0]);
						diff_list.push({name:L[0],value:L[1]})
					}
				}
			}
		}
	})
	if(diff_list.length > 0){
		fs.appendFile(source_file, "#时间："+getNowFormatDate() + "，差异追加如下：\n");
	}
	for( var i = 0; i < diff_list.length; ++i ){
		if (IP_REG.test(diff_list[i].value)) {
			IP_REG.lastIndex = 0;
			fs.appendFile(source_file, "#"+diff_list[i].name + "=" +  diff_list[i].value + "\n");
			value_of_diff_change = diff_list[i].value.replace(/((?:(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))\.){3}(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d))))/g,"localhost")
			fs.appendFile(source_file, diff_list[i].name + "=" +  value_of_diff_change + "\n");
		}else{
			fs.appendFile(source_file, diff_list[i].name + "=" +  diff_list[i].value + "\n");
		}
	}
})

