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);
});

function parseStr2Json(str){
	var a = {};
	var strs = str.split(" ");
	for(let i of strs){
		if(i){
			let os = i.split("|");
			a[os[0]]={
				name: os[0],
				ip: os[1],
				http: os[2],
				https: os[3]
			}
		}
	}
	return a
}

function parseJson2Str(json){
	var a = [];
	let keys = Object.keys(json);
	for(let k of keys){
		a.push([
			json[k].name,
			json[k].ip,
			json[k].http,
			json[k].https
		].join("|"))
	}
	return a.join(" ")
}


// 增加一个新的nginx映射
admin.post('/add_new_proxy', function (req, res) {
	let request = req.body;
	let new_namespace = request["namespace"],new_ip = request["ip"],new_ports=request["proxy_ports"];
	var str = String(execSync(`cat ../ngrok/docker_env_name.sh`)).replace(/\n/,"");
	let data = parseStr2Json(str);
	data[new_namespace] = {
		name: new_namespace,
		ip: new_ip,
		http: new_ports.http_port,
		https: new_ports.https_port
	}
	
	let s = parseJson2Str(data)
	s = s.replace("\n","")
	execSync(`echo "${s}" > ../ngrok/docker_env_name.sh`)
	cproc.exec("../ngrok/make_frp_ini_V2.sh");
	res.send({msg:"执行完成"});
});


// 删除一个namespace映射
admin.post('/remove_proxy', function (req, res) {
	let request = req.body;
	let new_namespace = request["namespace"];
	var str = String(execSync(`cat ../ngrok/docker_env_name.sh`)).replace(/\n/,"");
	let data = parseStr2Json(str);
	delete data[new_namespace]
	let s = parseJson2Str(data)
	s = s.replace("\n","")
	execSync(`echo "${s}" > ../ngrok/docker_env_name.sh`)
	cproc.exec("../ngrok/make_frp_ini_V2.sh");
	res.send({msg:"执行完成"});
});

// 获取现有映射关系
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)






