var express = require('express');
var cproc = require('child_process');
var bodyParser = require('body-parser');
var execSync = cproc.execSync;
var options = {
  inflate: true,
  limit: '100kb',
  type: 'application/octet-stream'
};

var app = express();
var admin = express(); // the sub app
app.use(bodyParser.urlencoded({ extended: false }))

app.use(bodyParser.json())
var attrs = {
	configPath:"config_file",
	buildCmd:"command",
	gitPath:"git_path",
	gitGroup:"gitPathHead",
	host:"www",
	projectType:"type",
	projectAuth:"auth",
	projectDesc:"desc",
	logName:"log_name",
	jarFilePath:"target_path"
}
var attrComs = Object.keys(attrs)
var attrComsArr = [];
for(let i of attrComs){
	attrComsArr.push(attrs[i]);
}
admin.get('/get_node_command/:name', function (req, res) {
 	res.setHeader("Content-Type","application/json");
	var str = execSync(`node ./get_project_config.js  -name ${req.params.name} -attr config_file/command/gitPathHead`)
	var items = String(str).replace(/\n/g,"").split("|"); 
 	var config_file = items[0].replace(/\^/g," ");
	var command  = items[1].replace(/\^/g," ");
	var gitGroup = items[2].replace(/\^/g," ");
	res.send({configPath:config_file,buildCmd:command,gitGroup:gitGroup});
});

admin.get('/get_project_attr/:name', function (req, res) {
 	res.setHeader("Content-Type","application/json");
	var comstr = attrComsArr.join("/");
	var names = req.params.name.split("--");
	var p_name = "";
	if(names.length > 1){
		p_name = names[0]
	}else{
		p_name = req.params.name
	}
	var str = execSync(`node ./get_project_config.js  -name ${p_name} -attr ${comstr}`)
	var items = String(str).replace(/\n/g,"").split("|"); 
	let rs = {},index = 0;
	for(let i of items){
		rs[attrComs[index]] = i.replace(/\^/g," ");
		index++
	}
	res.send(rs);
});

admin.get('/get_hosts', function (req, res) {
 	res.setHeader("Content-Type","application/json");
	var comstr = attrComsArr.join("/");
	var str = execSync(`node ./get_project_config.js  -type hosts`)
	var items = String(str); 
	res.send(items);
});

admin.post('/add_new_proxy', function (req, res) {
	let request = req.body;
	var str = String(execSync(`cat ../ngrok/docker_env_name.sh`)).replace(/\n/,"");
	var index = str.indexOf(request["namespace"])
	let newstr = "",sourcestr;
	if( index != -1 ){
		//存在这个配置，判断是否是原有的IP
		var reg = new RegExp(request["namespace"] + "\\|\\d*\\.\\d*\\.\\d*\\.\\d*");
		try{
			sourcestr = str.match(reg);
			sourcestr = sourcestr[0]
		}catch(e){
			res.send({msg:"错误，请检查 docket_env_name.sh 文件"})
			return
		}
		if(sourcestr != undefined){
			var items = sourcestr.split("|");
			if(items[1] == request["ip"]){
				res.send({msg:"已经存在的配置"});
				return 
			}else{
				targetstr = request["namespace"] + "|" +  request["ip"];
				newstr = str.replace(sourcestr,targetstr);
			}
		}else{
			res.send({msg:"错误1"})
			return 
		}
	}else{
		newstr = str + " " + request["namespace"] + "|" +  request["ip"];
		//文件添加到这里面
	}
	newstr = newstr.replace(/\n/,"");
	execSync(`echo "${newstr}" > ../ngrok/docker_env_name.sh`)
	cproc.exec("../ngrok/make_frp_ini.sh");
	res.send({msg:"执行完成"});
});

admin.post('/remove_proxy', function (req, res) {
	let request = req.body;
	var str = String(execSync(`cat ../ngrok/docker_env_name.sh`)).replace(/\n/,"");
	var sourcestr;
	var reg = new RegExp(request["namespace"] + "\\|\\d*\\.\\d*\\.\\d*\\.\\d*");
	try{
		sourcestr = str.replace(reg,"");
	}catch(e){
		res.send({msg:"错误，请检查 docket_env_name.sh 文件"})
		return
	}
	execSync(`echo "${sourcestr}" > ../ngrok/docker_env_name.sh`);
	cproc.exec("../ngrok/make_frp_ini.sh");
	
 	res.setHeader("Content-Type","application/json");
	var str = execSync(`cat ../ngrok/docker_env_name.sh`)
	res.send({namespace:String(str)});
});


admin.get('/get_proxy', function (req, res) {
 	res.setHeader("Content-Type","application/json");
	var str = execSync(`cat ../ngrok/docker_env_name.sh`)
	res.send({namespace:String(str)});
});

app.use('/config_server', admin)
console.log("http://192.168.4.3:10088/config_server/get_node_command") 
app.listen(10088)






