#!/bin/sh

if [ "$1" = "y" ]; then
  echo "输入用户名"
  user=$(./get-char.sh)

  echo "输入密码"
  password=$(./get-char.sh)
fi

ROOT_SHELL_FOLDER=$(pwd)

BUILD_ENV="-test"
BUILD_ENV_MOBILE="test"

productDirArray=(
"packages/cost"
"packages/party-service"
"packages/hg-config"
"packages/cost-mobile"
#"packages-app/app-h5-main"
#"packages-h5/h5-weeks-show"
#"help/help"
)

funEcho(){
  UNAME=$(uname -s)
  WINNAME="Linux"

  if [[ $UNAME == *$WINNAME* ]]; then
    echo -e "$1"
  else
    echo "$1"
  fi
}

funGitPull(){

  CURR_ROOT_DIR=$(pwd)

  DIR=/home/Desktop/consult-cloud-hg-fe/release-test

  cd ${DIR}

  GITNAME=`git symbolic-ref --short -q HEAD`

  if [ "release-test" != "${GITNAME}" ]; then
    funEcho "${DIR} 仓库"
    funEcho "当前分支:${GITNAME}"
    funEcho "不在 release-test 分支上！！！"
    exit 1
  fi

  if [ ! -f "./git.sh" ]; then
      funEcho "\033[1;33;41m ./git.sh文件不存在 \033[0m"
      exit 1
  fi

  if [ ! -x "./git.sh" ]; then
      chmod +x ./git.sh
  fi

  ./git.sh

  cd ${CURR_ROOT_DIR}

}

funGitPull ${BUILD_ENV}

cd ${ROOT_SHELL_FOLDER}

IS_thread_FILE=${ROOT_SHELL_FOLDER}/thread.flag.suo

for productDir in ${productDirArray[@]}; do
    if [ -d "./${productDir}" ]; then
        if [ -f "./${productDir}/build.sh" ]; then
            cd "./${productDir}"
            if [ ! -x "./${productDir}/build.sh" ]; then
                chmod +x ./build.sh
            fi

            if [ -f "${IS_thread_FILE}" ]; then
              ./build.sh ${BUILD_ENV} ${BUILD_ENV_MOBILE} &
            else
              ./build.sh ${BUILD_ENV} ${BUILD_ENV_MOBILE}
            fi
            pid=$!
            funEcho "\033[36m (PID=${pid})开始执行 ./${productDir}/build.sh ${BUILD_ENV}\033[0m"
            cd '../..'
        else
            funEcho "\033[1;33;41m ./${productDir}/build.sh 不存在或没有执行权限 \033[0m"
        fi
    else
        funEcho "\033[1;33;41m 项目包 ${productDir} 不存在 \033[0m"
    fi
done

if [ -f "${IS_thread_FILE}" ]; then
  wait
fi

funGitPull ${BUILD_ENV}

cd ${ROOT_SHELL_FOLDER}

if [ "$user" != "" ]; then
  if [ "$password" != "" ]; then
    history -c
    node ./release/release.js --evn=${BUILD_ENV_MOBILE} -u=$user -p=$password
    history -c
  fi
fi
exit 0
