if [ -d "${HOME}/.nvm/" ]
then
  . ${HOME}/.nvm/nvm.sh
fi

node_version="v16.18.0"

checkResult(){
  ret=$?
  if [ $ret != 0 ]
  then
    echo "[$1]执行失败"
    exit 2
    return 0
  else
    echo "[$1]执行成功"
    return 0
  fi
}

checkNode(){
  for line in `node -v` 
  do
  if [ $line != $node_version ]
  then
    echo "change Node from $line to $node_version"
    nvm use $node_version
    ret=$?
    if [ $ret != 0 ]
    then
      echo "Please run nvm install $node_version"
      exit 3
    else
      return 0
    fi
  else
    return 0
  fi
  done
}

setEnv(){
  echo "检查build_env:$build_env"
  if [ ! -n "$build_env" ]
  then
    read -p "选择环境 [1:本地调试] [2:测试] [3:生产] " apiEnv
    if [ $apiEnv = "2" ]
    then
      export build_env="dev"
    fi
    if [ $apiEnv = "3" ]
    then
      export build_env="prod"
    fi
    if [ $apiEnv != "2" && $apiEnv != "3" ]
    then
      export build_env="localdebug"
    fi
  fi
  echo "编译环境:$build_env"
}

setMock(){
  echo "检查mock:$mock"
  if [ ! -n "$mock" ]
  then
    read -p "是否打开mock [1:打开] [2:不打开] " mockOpen
    export mock=0
    if [ $mockOpen = "1" ]
    then
      export mock=1
    fi
  fi
  echo "mock开关:$mock"
}

setNpmSetup(){
  echo "检查noSkipNpmInstall:$noSkipNpmInstall"
  if [  ! -n "$noSkipNpmInstall" ]
  then
    read -p "跳过环境初始化?[1]:不跳过,[其它]:跳过 " noSkipNpmInstall
  fi

  if [ $noSkipNpmInstall =  "1" ]
  then
    echo "开始npm install"
    npm config delete registry -g
    npm config delete registry
    npm install
    checkResult "npm install"
  else
    echo "跳过 npm install"
  fi
}

build(){  
  setEnv
  setMock
  setNpmSetup
  rm -rf __dirname/dist
  checkResult "清理dist"

  

  if [ $build_type =  "dev" ]
  then
    echo "开始npm run dev"
    npm run dev
    checkResult "npm run dev"
  else
    echo "开始npm run build"
    npm run build
    checkResult "npm run build"
  fi
}


checkNode
checkResult "检查node"

build
checkResult "start.sh"

