#!/bin/bash
project_type=$1
git_branch=$2
ip=$3
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`

function getCode()
{
	projects=(`node $config_server/get_project_config.js  -type $1 -attr name`)
	for project in ${projects[@]}
	do
		desc=`node $config_server/get_project_config.js  -name $project -attr desc`
		type=`node $config_server/get_project_config.js  -name $project_name -attr type`
        	if [ "$type" = "node" ];then
                	command2=`node $config_server/get_project_config.js  -name $project_name -attr command2`
                	$command2
        	fi
		cd $project_path
		project_folder=`find ./ -maxdepth 1 -name "$project"`
		if [ -n "$project_folder" ];then
			echo "sh $config_server/show_info.sh $project pull代码 $desc $3"
			sh $config_server/show_info.sh $project pull代码 $desc $3
			cd ./$project

			echo "git checkout ./"
			git checkout ./
			echo "git fetch"
			git fetch
			# echo "git pull"
			# git pull
			#如果拉代码失败，则获取现在所处分支，然后删掉现在的项目，重新clone
			if [ $? -ne 0 ]; then
        			echo "error: Pulling is not possible because you have unmerged files"
				git_branch=`git branch  | grep '*' | awk  '{print $2}'`
				echo $git_branch
				cd $project_path
				rm -rf $project_folder
				sh $config_server/show_info.sh $project clone代码 $desc $3
				git_path=`node $config_server/get_project_config.js  -name $project -attr git_path`
				git clone $git_path
				cd ./$project
			fi
			if [ -n "$git_branch" ] && [ $git_branch != "originalBBB" ]; then
				echo "git checkout -f $git_branch"
				git checkout -f $git_branch
				git_branch=$2
			fi
			git pull
			echo "git reset FETCH_HEAD --hard"
			git reset FETCH_HEAD --hard
			git branch
		else
			sh $config_server/show_info.sh $project clone代码 $desc $3
			git_path=`node $config_server/get_project_config.js  -name $project -attr git_path`
			git clone $git_path
		fi
	done
}

if [ "$project_type" = "java" ]
then
	getCode java
elif [ "$project_type" = "ui" ]
then
	getCode ui
elif [ "$project_type" = "node" ]
then
	getCode node
elif [ "$project_type" = "python" ]
then
	getCode python
else
	getCode java $2 $3
	getCode python $2 $3
	getCode node $2 $3
	getCode ui $2 $3
fi	
