#!/bin/bash
project_type=$1
branch_name=$2
public_ip=$3
ip=$4
if [ $branch_name = "aaa" ];then
	branch_name=""
fi

pwd_path="/home/qa-deploy-utils/qa_shell_script"
config_server="$pwd_path/config_server"
project_path=`cat $config_server/project_path.sh`
config_path=`cat $config_server/config_path.sh`

trap "exec 1000>&-;exec 1000<&-;exit 0" 2
tempfifo=$$.fifo
echo "mkfifo /tmp/$tempfifo"
mkfifo /tmp/$tempfifo
exec 1000<>/tmp/$tempfifo
rm -rf /tmp/$tempfifo

function deploy()
{
	for ((i=1; i<=4; i++))
	do
		echo >&1000
	done
	projects=(`node $config_server/get_project_config.js  -type $1 -attr name`)
	echo ${#projects[@]}"个"$1"项目:"  ${projects[@]}
	
	for project_name in ${projects[@]}
	do
		read -u1000
		{
			sh /home/qa-deploy-utils/qa_shell_script/2_get_code_by_name.sh $project_name "$branch_name" $ip
			if [ $? = 0 ]; then
				echo "--- $ip 2_get_code_by_name $project_name ok ---"
			else
				echo "--- $ip 2_get_code_by_name $project_name fail ---"
				echo >&1000
				exit -1
			fi
 
			sh /home/qa-deploy-utils/qa_shell_script/3_link_config_file_by_name.sh $project_name $public_ip $ip
			if [ $? = 0 ]; then
				echo "--- $ip 3_link_config_file_by_name $project_name ok ---"
			else
				echo "--- $ip 3_link_config_file_by_name $project_name fail ---"
				echo >&1000
				exit -1
			fi

			sh /home/qa-deploy-utils/qa_shell_script/4_build_by_name.sh $project_name $public_ip $ip
			if [ $? = 0 ]; then
				echo "--- $ip 4_build_by_name $project_name ok ---"
			else
				echo "--- $ip 4_build_by_name $project_name fail ---"
				echo >&1000
				exit -1
			fi

			sh /home/qa-deploy-utils/qa_shell_script/5_restart_by_name.sh $project_name $public_ip $ip
			if [ $? = 0 ]; then
				echo "--- $ip 5_restart_by_name $project_name ok ---"
			else
				echo "--- $ip 5_restart_by_name $project_name fail ---"
				echo >&1000
				exit -1
			fi
			echo >&1000
		}&
	done
	wait
}

if [ "$project_type" = "all" ]
then
	#projects=(`node $config_server/get_project_config.js  -type ui -attr name`)
        #echo ${#projects[@]}"个ui项目:"  ${projects[@]}
	#projects=(`node $config_server/get_project_config.js  -type java -attr name`)
        #echo ${#projects[@]}"个java项目:"  ${projects[@]}
	#projects=(`node $config_server/get_project_config.js  -type node -attr name`)
        #echo ${#projects[@]}"个node项目:"  ${projects[@]}
	#projects=(`node $config_server/get_project_config.js  -type python -attr name`)
        #echo ${#projects[@]}"个python项目:"  ${projects[@]}
	deploy node
	deploy ui
	deploy java
	deploy python
else
	deploy $project_type
fi
