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

if [ -z "$project_name" ];then
	echo "清输入项目名称"
	exit -1
fi

cd $project_path
project_folder=`find ./ -maxdepth 1 -name "$project_name"`
if [ -n "$project_folder" ];then
	desc=`node $config_server/get_project_config.js  -name $project_name -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
	sh $config_server/show_info.sh $project_name pull代码 $desc $3
	cd ./$project_name
	git checkout ./
	git fetch -p
	
	#git pull
	if [ -n "$git_branch" ]; then
		echo "checkout specified branch $git_branch"
		git checkout -f $git_branch
		if [ $? = 0 ]; then
			echo "checkout branch $git_branch is ok".
        		# git pull
        	else
       			echo "Fail to checkout branch $git_branch".
        		exit -1 
        	fi
	else
		#echo "checkout default branch master"
		#git checkout -f master
		git_branch=`git branch  | grep '*' | awk  '{print $2}'`
		echo "current branch: $git_branch"
		# git pull
	fi
	git fetch -p
	echo "git reset FETCH_HEAD --hard"
	git reset FETCH_HEAD --hard
else
	desc=`node $config_server/get_project_config.js  -name $project_name -attr desc`
	sh $config_server/show_info.sh $project_name clone代码 $desc $3
	echo "node $config_server/get_project_config.js  -name $project_name -attr git_path"
	git_path=`node $config_server/get_project_config.js  -name $project_name -attr git_path`
	echo "git clone $git_path"
	git clone $git_path
	cd ./$project_name
	if [ -n "$git_branch" ]; then
		echo "checkout specified branch $git_branch"
		git checkout -f $git_branch
		if [ $? = 0 ]; then
			echo "checkout branch $git_branch is ok".
        		git pull
        	else
       			echo "Fail to checkout branch $git_branch".
        		exit -1
        	fi
	fi
fi
