#!/bin/bash
#################################################
# 云协作Lite 自动安装和启动
# 运行 oneboxInstaller.sh --h 获取更多使用帮助
###################################

# For Ubuntu, make sure use bash instead of dash
if [ "$BASH_VERSION" = "" ]; then
	echo "$(tput setaf 1)请使用Bash运行此脚本，例如/bin/bash oneboxInstaller.sh$(tput sgr0)"
	exit 1
fi
function printHelp() {
	if [ "$IS_CENTOS" -eq 1 ]; then
		cmdStr="sh"
	else
		cmdStr="/bin/bash"
	fi
	printInfo "$APP_NAME 自动安装和启动脚本[1.1.0]。"
	printWarn "  注：！运行此脚本请确保Internet连接正常！"
	printWarn "  注：！此脚本需要在非root用户下运行，如果用root账户启动，此脚本会帮助用户创建一个带有root权限的用户！"
	printInfo "1, 此脚本会检测当前系统，并下载安装所需依赖，例如：JAVA，MongoDB等（安装过程中，如果缺失'系统依赖'，则需要当前账户有Root权限才能继续安装）"
	printInfo "2, 此脚本会自动下载并安装 ${APP_NAME} "
	printInfo "	 注：如果当前目录已经存在上述依赖安装包（手动下载的或者上次运行脚本下载的），则不会重复下载；但 ${APP_NAME} 安装包，会被删除重新下载安装。"
	printf "\n"
	printInfo "使用方法："
	printInfo "安装+启动"
	printInfo "	${cmdStr}  oneboxInstaller.sh"
	printInfo "	注：1，默认使用的是国内的地址或镜像，进行软件下载和安装，例如：淘宝NPM镜像等。如果想使用官方的下载地址或镜像，请指定 --official 参数，国内会消耗较长的时间"
	printInfo "	注：2，指定安装版本 --version v1.1"
	printInfo "启动所有服务（mongodb,elasticsearch和云协作lite）"
	printInfo "	${cmdStr}  oneboxInstaller.sh --onlyStart"
	printInfo "停掉所有服务（mongodb,elasticsearch和云协作lite）"
	printInfo "	${cmdStr}  oneboxInstaller.sh --onlyStop"
}

# Print Colorful message and steps
RED=$(tput setaf 1)
GREEN=$(tput setaf 2)
YELLOW=$(tput setaf 3)
NORMAL=$(tput sgr0)
STEP=1
function printError() {
	printf '%s%s\n' "$RED" "$1" "$NORMAL"
}
function printStep() {
	printf '%s%s\n' "$GREEN" "$STEP -- $1" "$NORMAL"
	((STEP++))
}
function printInfo() {
	printf '%s%s\n' "$NORMAL" "$1" "$NORMAL"
}
function printSuccess() {
	printf '%s%s\n' "$GREEN" "$1" "$NORMAL"
}
function printWarn() {
	printf '%s%s\n' "$YELLOW" "$1" "$NORMAL"
}
# exit method to submit the script execution statistics
exitFromScript() {
	exitNum=0
	if [ ! -z "${1}" ]; then
		exitNum=${1}
	fi
	if [ ! -z "${2}" ]; then
		printError "${2}"
	fi
	if [ ${IS_DEBUG} -eq 0 ]; then
		wget "https://rlogs.youdao.com/rlog.php?_npid=BaiChuan&_ncat=event&event_id=autoScript_run" -0 /dev/null -o /dev/null >/dev/null 2>&1
		if [ "${exitNum}" -eq ${CODE_SUCCESS} ]; then
			wget "https://rlogs.youdao.com/rlog.php?_npid=BaiChuan&_ncat=event&event_id=autoScript_success" -0 /dev/null -o /dev/null >/dev/null 2>&1
		elif [ "${exitNum}" -eq ${CODE_FAILURE} ]; then
			wget "https://rlogs.youdao.com/rlog.php?_npid=BaiChuan&_ncat=event&event_id=autoScript_fail" -0 /dev/null -o /dev/null >/dev/null 2>&1
		fi
	fi
	exit "${exitNum}"
}
# check the script parameters if required
function paramValueCheck() {
	paramValue="$1"
	paramName="$2"
	if [ -z "$paramValue" ] || [[ $paramValue == --* ]]; then
		printError "no param value for $paramName"
		exitFromScript ${CODE_OTHER}
	fi
}
# check the process existence according the key words, which use 'grep' to do it
function checkProcess() {
	# check the args
	if [ "$1" == "" ]; then
		return 0
	fi

	procNum=$(ps -ef | grep "$1" | grep -v "grep" | wc -l)
	if [ "$procNum" -ge 1 ]; then
		return 1
	else
		return 0
	fi
}
# check cpu is x64 or x86
function checkCpuBit() {
	bit64=$(uname -m)
	if [ "${bit64}" == "x86_64" ]; then
		return 1
	else
		return 0
	fi
}
# check whether the script is running by root user
function checkRoot() {
	userId=$(id -u)
	if [ "$userId" -eq 0 ]; then
		IS_SUDOER=1
		# 如果是Root用户，则需要创建一个带Root权限的新用户，之后提示用新用户重新执行此脚本
		read -r -p "此脚本需要在非Root账户下运行，是否创建一个新的带Root权限的用户来运行脚本（y/n）：" YorN
		if [ "$YorN" != "y" ] && [ "$YorN" != "Y" ]; then
			sudo chmod a+x oneboxInstaller.sh
			printSuccess "请切换到一个具有root权限的非root用户，并重新运行此脚本。"
			exitFromScript ${CODE_OTHER}
		fi
		read -r -p "请输入新用户名称（默认为 baichuan）：" userName
		if [ "$userName" == "" ]; then
			userName="baichuan"
		fi
		# if has dup account, delete it
		sudo userdel "$userName" >/dev/null 2>&1
		sudo rm -rf /home/$userName >/dev/null 2>&1
		printInfo "创建新用户：$userName"
		printWarn "请根据提示输入新用户的密码"
		sudo useradd "$userName"
		sudo passwd "$userName"
		printInfo "将脚本迁移到新建用户的根目录：/home/$userName"
		sudo mv oneboxInstaller.sh /home/$userName
		printInfo "修改脚本所有者为：$userName"
		sudo chown $userName: /home/$userName/oneboxInstaller.sh
		printInfo "给新创建用户赋予root权限"
		if [ "$IS_CENTOS" -eq 1 ]; then
			sudo usermod -aG wheel $userName
			getent group wheel | grep $userName && userReady=1 || userReady=0
		elif [ "$IS_UBUNTU" -eq 1 ]; then
			sudo usermod -aG sudo $
			getent group sudo | grep $userName && userReady=1 || userReady=0
		fi

		if [ "$userReady" -eq 0 ]; then
			printError "新用户准备失败"
			exitFromScript ${CODE_FAILURE}
		else
			if [ "$OS_VERSION" -eq "$CENT6" ]; then
				printWarn "当前为CentOS 6.X无法自动赋予Root权限，请参照帮助文档（ ${MANUAL_HELP_URL} ），如何在CentOS 6.x创建具有Root权限的用户"
			fi
			printWarn "请通过如下命令，切换到新建账号，然后重新运行此脚本："
			printInfo "  su $userName"
			printInfo "  cd ~"
			exitFromScript ${CODE_OTHER}
		fi
	fi
}
# check whether current user has Root Permissions
function checkSudoer() {
	componentName="$1"
	if [ -z "$2" ]; then
		notExit=0
	else
		notExit=$2
	fi

	if [ "$IS_SUDOER" -eq 0 ]; then
		userName=$(whoami)
		if [ "$OS_VERSION" == "$CENT7" ]; then
			getent group wheel | grep "${userName}" && IS_SUDOER=1
		elif [ "$IS_UBUNTU" -eq 1 ]; then
			getent group sudo | grep "${userName}" && IS_SUDOER=1
		fi
		if [ "$IS_SUDOER" -eq 0 ]; then
			printWarn "验证当前用户是否有root权限。可能需要输入当前账户的密码"
			sudo -v >/dev/null 2>&1 && IS_SUDOER=1
		fi
	fi

	if [ "$notExit" -ne 1 ] && [ "$IS_SUDOER" -eq 0 ]; then
		printError "系统依赖 ${componentName} 命令缺失，且当前用户不具备Root权限，无法继续。"
		printWarn "请使用具有Root权限的非root用户运行此脚本，安装所需依赖，或者参见帮助文档（${MANUAL_HELP_URL}）中的'安装前的准备工作'，手动安装，之后在运行此脚本。"
		printWarn "具有Root权限账户的创建，请参见上述帮助文档链接里‘附件’部分，关于‘如何在CentOS上创建具有root权限的账号’的信息"
		exitFromScript ${CODE_FAILURE}
	fi
}

# start mongod which will check whether baichuan mongod has been started before start
function startDB() {
	if [ ! -d "$ROOT_FOLDER/data" ]; then
		mkdir "$ROOT_FOLDER/data"
	fi
	if [ ! -d "$ROOT_FOLDER/data/db" ]; then
		mkdir "$ROOT_FOLDER/data/db"
	fi
	if [ ! -d "$ROOT_FOLDER/data/log" ]; then
		mkdir "$ROOT_FOLDER/data/log"
	fi

	dbLocation=$1
	checkProcess "$ROOT_FOLDER/data/log/baichuan_db.log"
	dbRunning=$?
	if [ $dbRunning -eq 0 ]; then
		printInfo "启动数据库 ..."
		FailedToStart=0
		if [ "$dbLocation" -eq 0 ]; then
			# 数据库全局安装
			cmdStr="mongod"
		else
			# 数据库本地安装
			cmdStr="$ROOT_FOLDER/$DB_FOLDER/bin/mongod"
		fi

		cmdStr+=" --dbpath $ROOT_FOLDER/data/db --logpath $ROOT_FOLDER/data/log/baichuan_db.log --fork"
		if [ ${IS_DEBUG} -eq 1 ]; then
			printInfo "$cmdStr"
		fi
		if eval "$cmdStr"; then
			sleepTime=30
			while [ $sleepTime -gt 0 ]; do
				sleep 5
				checkProcess "$ROOT_FOLDER/data/log/baichuan_db.log"
				dbRunning=$?
				if [ $dbRunning -eq 1 ]; then
					printSuccess "数据库启动成功"
					break
				else
					((sleepTime -= 5))
				fi
			done
			if [ $sleepTime -le 0 ]; then
				FailedToStart=1
			fi
		else
			FailedToStart=1
		fi

		if [ $FailedToStart -eq 1 ]; then
			printError "启动数据库失败。"
			checkProcess "mongod"
			dbRunning=$?
			if [ $dbRunning -eq 1 ]; then
				printError "检测到其它mongod实例，请确认是否有端口冲突。"
			fi
			printWarn "数据库启动日志："
			logInfo=$(cat "$ROOT_FOLDER/data/log/baichuan_db.log")
			echo "$logInfo"
			exitFromScript ${CODE_FAILURE}
		fi
	else
		printSuccess "数据库已启动"
	fi
}
function stopDB() {
	printWarn "停止MongoDB服务"
	kill -2 $(ps -ef | grep "${ROOT_FOLDER}/data/log/baichuan_db.log" | grep -v "grep" | awk '{print $2}') >/dev/null 2>&1
}
function installESPlugin() {
	cmdStr="$ROOT_FOLDER/$ES_PACKAGE_PREFIX/bin/elasticsearch-plugin install"
	cmdStr+=" file:///$ROOT_FOLDER/$ES_PLUGIN_PACKAGE"
	executeCmd "$cmdStr" 0
	if [ ! -d "$ROOT_FOLDER/$ES_PACKAGE_PREFIX/plugins/analysis-ik" ]; then
		printError "安装ES插件失败，请手动尝试此命令：$cmdStr"
		exitFromScript ${CODE_FAILURE}
	fi
}
function startES() {
	checkProcess "$ROOT_FOLDER/$ES_PACKAGE_PREFIX/config"
	esRunning=$?
	if [ $esRunning -eq 0 ]; then
		printInfo "启动ES ..."
		FailedToStart=0
		cmdStr="$ROOT_FOLDER/$ES_PACKAGE_PREFIX/bin/elasticsearch -d"
		if [ ${IS_DEBUG} -eq 1 ]; then
			printInfo "$cmdStr"
		fi
		if ! eval "$cmdStr"; then
			FailedToStart=1
		else
			sleepTime=30
			while [ $sleepTime -gt 0 ]; do
				sleep 5
				checkProcess "$ROOT_FOLDER/$ES_PACKAGE_PREFIX/config"
				esRunning=$?
				if [ $esRunning -eq 1 ]; then
					printSuccess "ES启动成功"
					break
				else
					((sleepTime -= 5))
				fi
			done
			if [ $sleepTime -le 0 ]; then
				FailedToStart=1
			fi
		fi
		if [ $FailedToStart -eq 1 ]; then
			printError "启动ES失败($cmdStr)"
			if [ -f "${ROOT_FOLDER}/${ES_PACKAGE_PREFIX}/logs/elasticsearch.log" ]; then
				logInfo=$(cat "${ROOT_FOLDER}/${ES_PACKAGE_PREFIX}/logs/elasticsearch.log")
				printWarn "系统启动日志："
				echo "$logInfo"
			fi
			exitFromScript ${CODE_FAILURE}
		fi
	else
		printSuccess "ES已启动"
	fi
}
function stopES() {
	printWarn "停止ElasticSearch服务"
	kill $(ps -ef | grep "${ROOT_FOLDER}/${ES_PACKAGE_PREFIX}/config" | grep -v "grep" | awk '{print $2}') >/dev/null 2>&1
}
# download resource from online
# 如果有return值：0代表成功，1代表失败
function download() {
	URL="$1"
	packageName="$2"
	if [ -z "$3" ]; then
		notExit=0
	else
		notExit=$3
	fi
	if [ ! -f "${ROOT_FOLDER}/${packageName}" ]; then
		printInfo "下载中： $URL"
		wget "$URL"
		if [ ! -f "${ROOT_FOLDER}/${packageName}" ]; then
			printError "下载失败：$URL"
			if [ "$notExit" -eq 1 ]; then
				return 1
			else
				exitFromScript ${CODE_FAILURE}
			fi
		fi
	fi
	return 0
}
function executeCmd() {
	cmdStr="$1"
	if [ -z "$2" ]; then
		showOutput=0
	else
		showOutput=$2
	fi
	if [ "$IS_DEBUG" -eq 1 ]; then
		printInfo "$cmdStr"
	fi
	if [ "$showOutput" -eq 0 ]; then
		if ! eval "$cmdStr" >/dev/null 2>&1; then
			printError "命令执行失败($cmdStr)"
			exitFromScript ${CODE_FAILURE}
		fi
	else
		if ! eval "$cmdStr"; then
			printError "命令执行失败($cmdStr)"
			exitFromScript ${CODE_FAILURE}
		fi
	fi
}
function checkOSVersion() {
	OS_VERSION=""
	VersionFile="/etc/centos-release"
	if [ "$OS_VERSION" == "" ] && [ -f $VersionFile ]; then
		ISSUE_INFO=$(cat $VersionFile)
		if [ "$IS_DEBUG" -eq 1 ]; then
			printInfo "系统版本：$ISSUE_INFO"
		fi
		grep -q "CentOS release 6." $VersionFile && OS_VERSION=$CENT6
		if [ "$OS_VERSION" == "$CENT6" ]; then
			IS_CENTOS=1
			return
		fi
		grep -q "CentOS Linux release 7" $VersionFile && OS_VERSION=$CENT7
		if [ "$OS_VERSION" == "$CENT7" ]; then
			IS_CENTOS=1
			return
		fi
	fi
	VersionFile="/etc/issue"
	if [ "$OS_VERSION" == "" ] && [ -f $VersionFile ]; then
		ISSUE_INFO=$(cat $VersionFile)
		if [ "$IS_DEBUG" -eq 1 ]; then
			printInfo "系统版本：$ISSUE_INFO"
		fi
		grep -q "Ubuntu 14." $VersionFile && OS_VERSION=$UB14
		if [ "$OS_VERSION" == "$UB14" ]; then
			IS_UBUNTU=1
			return
		fi
		grep -q "Ubuntu 16." $VersionFile && OS_VERSION=$UB16
		if [ "$OS_VERSION" == "$UB16" ]; then
			IS_UBUNTU=1
			return
		fi
	fi
	if [ "$OS_VERSION" == "" ]; then
		printError "无法确定当前系统信息"
		exitFromScript ${CODE_FAILURE}
	fi
}
function checkJAVAVersion() {
	rawVersion=$(java -version 2>&1)
	version=$(echo "$rawVersion" | head -n 1 | cut -d'"' -f2 | cut -d'.' -f2)
	if [ "$version" -ge 8 ]; then
		return 1
	else
		printWarn "系统当前JAVA版本过低：${rawVersion}"
		return 0
	fi
}
function checkNodejsVersion() {
	rawVersion=$(node --version 2>&1)
	version=$(echo "${rawVersion}" | head -n 1 | cut -d'v' -f2 | cut -d'.' -f1)
	if [ "$version" -ge "8" ]; then
		return 1
	else
		printWarn "系统当前Nodejs版本过低：${rawVersion}"
		return 0
	fi
}
function installMongodbByPM() {
	printInfo "在线安装Mongodb数据库 ..."
	printWarn "安装过程中需要Root权限，可能需要输入当前账户的密码"
	if [ "$IS_CENTOS" -eq 1 ]; then
		sudo touch /etc/yum.repos.d/mongodb-org.repo
		echo "[mongodb-org]" | sudo tee /etc/yum.repos.d/mongodb-org.repo
		echo "name=MongoDB Repository" | sudo tee --append /etc/yum.repos.d/mongodb-org.repo
		if [ "$OS_VERSION" == "$CENT7" ]; then
			if [ "$OFFICIAL_DOWNLOAD" -eq 1 ]; then
				echo "baseurl=https://repo.mongodb.org/yum/redhat/7Server/mongodb-org/3.6/x86_64/" | sudo tee --append /etc/yum.repos.d/mongodb-org.repo
			else
				echo "baseurl=http://mirrors.aliyun.com/mongodb/yum/redhat/7Server/mongodb-org/3.6/x86_64/" | sudo tee --append /etc/yum.repos.d/mongodb-org.repo
			fi
		elif [ "$OS_VERSION" == "$CENT6" ]; then
			if [ "$OFFICIAL_DOWNLOAD" -eq 1 ]; then
				echo "baseurl=https://repo.mongodb.org/yum/redhat/6Server/mongodb-org/3.6/x86_64/" | sudo tee --append /etc/yum.repos.d/mongodb-org.repo
			else
				echo "baseurl=http://mirrors.aliyun.com/mongodb/yum/redhat/6Server/mongodb-org/3.6/x86_64/" | sudo tee --append /etc/yum.repos.d/mongodb-org.repo
			fi
		fi
		if [ "$OFFICIAL_DOWNLOAD" -eq 1 ]; then
			echo "gpgcheck=1" | sudo tee --append /etc/yum.repos.d/mongodb-org.repo
			echo "gpgkey=https://www.mongodb.org/static/pgp/server-3.6.asc" | sudo tee --append /etc/yum.repos.d/mongodb-org.repo
		else
			echo "gpgcheck=0" | sudo tee --append /etc/yum.repos.d/mongodb-org.repo
		fi
		echo "enabled=1" | sudo tee --append /etc/yum.repos.d/mongodb-org.repo
		sudo yum -y update
		sudo yum -y install mongodb-org
	elif [ "$IS_UBUNTU" -eq 1 ]; then
		sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 2930ADAE8CAF5059EE73BB4B58712A2291FA4AD5
		if [ "$OS_VERSION" == "$UB14" ]; then
			if [ "$OFFICIAL_DOWNLOAD" -eq 1 ]; then
				echo "deb [ arch=amd64 ] https://repo.mongodb.org/apt/ubuntu trusty/mongodb-org/3.6 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.6.list
			else
				echo "deb [ arch=amd64 ] http://mirrors.aliyun.com/mongodb/apt/ubuntu trusty/mongodb-org/3.6 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.6.list
			fi
		else
			if [ "$OFFICIAL_DOWNLOAD" -eq 1 ]; then
				echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu xenial/mongodb-org/3.6 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.6.list
			else
				echo "deb [ arch=amd64,arm64 ] http://mirrors.aliyun.com/mongodb/apt/ubuntu xenial/mongodb-org/3.6 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.6.list
			fi
		fi
		sudo apt-get -y update
		sudo apt-get -y install mongodb-org
	else
		printError "不支持的操作系统类型：$OS_VERSION"
	fi
	if ! command -v mongod >/dev/null 2>&1; then
		printError "在线安装数据库失败"
		return 1
	fi
	startDB 0
	return 0
}
function installMongodbLocally() {
	printInfo "解压安装Mongodb( $dbPackage )"
	dbPackage=$1
	dbPackagePrefix=$2
	rm -rf "$DB_FOLDER"
	cmdStr="tar -xvf $dbPackage"
	executeCmd "$cmdStr" 0
	mv "$dbPackagePrefix" "$DB_FOLDER"
	if [ ! -d "$DB_FOLDER" ]; then
		printError "解压安装数据库失败"
		return 1
	fi
	startDB 1
	return 0
}
# 安装顺序：
# 1，如果本地已有安装包，则直接安装
# 2，如果本地没有安装包，则尝试下载安装（分别尝试百川共享和在线官网）
# 3，如果下载失败但有Root权限，尝试安装工具在线安装
# 4，提示安装失败
function installMongodb() {
	downloadURL_Official=""
	downloadURL_Share=""
	dbPackage=""
	dbPackagePrefix=""
	installOK=0
	if [ "$OS_VERSION" == "$CENT6" ]; then
		dbPackage=$DB_PACKAGE_CENT6
		dbPackagePrefix=$DB_PACKAGE_PREFIX_CENT6
		if [ ! -f "$ROOT_FOLDER/$DB_PACKAGE_CENT6" ]; then
			downloadURL_Official=$DB_URL_CENT6
			downloadURL_Share=$DB_URL_CENT6_SHARE

		fi
	elif [ "$OS_VERSION" == "$CENT7" ]; then
		dbPackage=$DB_PACKAGE_CENT7
		dbPackagePrefix=$DB_PACKAGE_PREFIX_CENT7
		if [ ! -f "$ROOT_FOLDER/$DB_PACKAGE_CENT7" ]; then
			downloadURL_Official=$DB_URL_CENT7
			downloadURL_Share=$DB_URL_CENT7_SHARE
		fi
	elif [ "$OS_VERSION" == "$UB14" ]; then
		dbPackage=$DB_PACKAGE_UB14
		dbPackagePrefix=$DB_PACKAGE_PREFIX_UB14
		if [ ! -f "$ROOT_FOLDER/$DB_PACKAGE_UB14" ]; then
			downloadURL_Official=$DB_URL_UB14
			downloadURL_Share=$DB_URL_UB14_SHARE
		fi
	elif [ "$OS_VERSION" == "$UB16" ]; then
		dbPackage=$DB_PACKAGE_UB16
		dbPackagePrefix=$DB_PACKAGE_PREFIX_UB16
		if [ ! -f "$ROOT_FOLDER/$DB_PACKAGE_UB16" ]; then
			downloadURL_Official=$DB_URL_UB16
			downloadURL_Share=$DB_URL_UB16_SHARE
		fi
	else
		printError "不支持的系统类型： $OS_VERSION"
		exitFromScript ${CODE_FAILURE}
	fi
	# 首先检测本地安装包是否已经存在
	if [ "$downloadURL_Share" == "" ]; then
		# 安装包已经存在，解压安装
		installMongodbLocally "$dbPackage" "$dbPackagePrefix"
		if [ $? -eq 0 ]; then
			installOK=1
		fi
	fi
	# 再次检测是否可以下载安装
	if [ "$installOK" -eq 0 ]; then
		# 当前账户没有Root权限或者在线安装失败，则下载安装
		if [ "$OFFICIAL_DOWNLOAD" -eq 0 ]; then
			download "$downloadURL_Share" "$dbPackage" 1
		fi
		if [ ! -f "${ROOT_FOLDER}/${dbPackage}" ]; then
			download "$downloadURL_Official" "$dbPackage"
		fi
		if [ -f "${ROOT_FOLDER}/${dbPackage}" ]; then
			installMongodbLocally "$dbPackage" "$dbPackagePrefix"
			if [ $? -eq 0 ]; then
				installOK=1
			fi
		fi
	fi
	# 然后检测是否可以在线安装
	if [ "$installOK" -eq 0 ]; then
		checkSudoer "mongodb" 1
		if [ "$IS_SUDOER" -eq 1 ]; then
			# 当前账户具有Root权限，选择yum/apt-get安装
			installMongodbByPM
			if [ $? -eq 0 ]; then
				installOK=1
			fi
		fi
	fi
	if [ "$installOK" -eq 0 ]; then
		printWarn "请参考帮助文档（ $MANUAL_HELP_URL ）中的'安装MongoDB'，手动安装JAVA依赖，之后重新运行此脚本。"
		exitFromScript ${CODE_FAILURE}
	fi
}
# Test Purpose
function cleanEnv() {
	if [ "$IS_CENTOS" -eq 1 ]; then
		sudo yum -y remove $JAVA_YUM_NAME*
		sudo yum -y remove python
		sudo yum -y remove make
		sudo yum -y remove unzip
		sudo yum -y remove wget
		sudo yum remove mongodb-org*
		if [ "$OS_VERSION" == "$CENT7" ]; then
			sudo yum -y autoremove
		fi
	elif [ "$IS_UBUNTU" -eq 1 ]; then
		sudo apt-get -y remove "$JAVA_APT_NAME"
		sudo apt-get -y remove python
		sudo apt-get -y remove make
		sudo apt-get -y remove unzip
		sudo apt-get -y remove wget
		sudo apt-get -y autoremove
	else
		printError "不支持的操作系统：$OS_VERSION"
		exitFromScript ${CODE_FAILURE}
	fi
	kill $(ps -ef | grep "$PM2_INST_NAME" | grep -v "grep" | awk '{print $2}')
	stopES
	stopDB

	rm -rf "${ROOT_FOLDER}/${JAVA_FOLDER}"
	rm -rf "${ROOT_FOLDER}/${JAVA_PACKAGE}"
	rm -rf mongodb-*
	rm -rf elasticsearch-*
	rm -rf node-*
	rm -rf baichuan-*
	rm -rf data
}

# 返回0，代表安装成功
# 返回1，代表安装失败
function installNodeLocally() {
	rm -rf "${ROOT_FOLDER}/${NODE_FOLDER}"
	cmdStr="tar -xvf $NODE_PACKAGE"
	executeCmd "$cmdStr" 0
	mv "$NODE_PACKAGE_PREFIX" "$NODE_FOLDER"
	if [ ! -d "${ROOT_FOLDER}/${NODE_FOLDER}" ]; then
		printError "解压安装Nodejs包（ ${NODE_PACKAGE} ）失败"
		return 1
	fi
	return 0
}
function installESLocally() {
	rm -rf "${ROOT_FOLDER}/${ES_PACKAGE_PREFIX}"
	cmdStr="tar -xvf $ES_PACKAGE"
	executeCmd "$cmdStr" 0
	if [ ! -f "${ROOT_FOLDER}/${ES_PACKAGE_PREFIX}/bin/elasticsearch" ]; then
		printError "安装ES失败"
		printWarn "请参考帮助文档（ ${MANUAL_HELP_URL} ）中的'安装elasticsearch'，手动安装，之后重新运行此脚本。"
		exitFromScript ${CODE_FAILURE}
	fi
	installESPlugin
	startES
}
# 返回0，代表安装成功
# 返回1，代表安装失败
function installJAVALocally() {
	rm -rf "${ROOT_FOLDER}/${JAVA_FOLDER}"
	cmdStr="tar -xvf $JAVA_PACKAGE"
	executeCmd "$cmdStr" 0
	if [ -f "${ROOT_FOLDER}/${JAVA_FOLDER}/bin/java" ]; then
		return 0
	fi
	return 1
}
# 安装插件解压依赖的组件：antiword, xpdf
function installFileExtractTools() {
	# install AntiWord
	if ! command -v antiword >/dev/null 2>&1; then
		checkSudoer 'antiword'
		if [ "$OS_VERSION" == "$CENT6" ]; then
			download ${ANTIWORD_URL_CENTOS6_SHARE} ${ANTIWORD_PACKAGE_CENTOS6} 1
			if [ $? -eq 1 ]; then
				printWarn "从官网下载'ANTIWORD'"
				download ${ANTIWORD_URL_CENTOS6} ${ANTIWORD_PACKAGE_CENTOS6}
			fi
			sudo yum -y localinstall ${ANTIWORD_PACKAGE_CENTOS6}
		elif [ "$OS_VERSION" == "$CENT7" ]; then
			download ${ANTIWORD_URL_CENTOS7_SHARE} ${ANTIWORD_PACKAGE_CENTOS7} 1
			if [ $? -eq 1 ]; then
				printWarn "从官网下载'ANTIWORD'"
				download ${ANTIWORD_URL_CENTOS7} ${ANTIWORD_PACKAGE_CENTOS7}
			fi
			sudo yum -y localinstall ${ANTIWORD_PACKAGE_CENTOS7}
		elif [ "$IS_UBUNTU" -eq 1 ]; then
			sudo apt-get -y update
			sudo apt-get -y install antiword
		fi
	fi
	if ! command -v antiword >/dev/null 2>&1; then
		printError "安装antiword失败"
		exitFromScript ${CODE_FAILURE}
	fi
	if [ ! -d "$XPDF_FOLDER" ]; then
		if [ ! -f "$XPDF_PACKAGE" ]; then
			download "$XPDF_URL" "$XPDF_PACKAGE" 1
			if [ $? -eq 1 ]; then
				printWarn "从官网下载'XPDF'"
				download ${XPDF_URL_SHARE} ${XPDF_PACKAGE}
			fi
		fi
		cmdStr="tar -xvf $XPDF_PACKAGE"
		executeCmd "$cmdStr" 0
		pathRef="${ROOT_FOLDER}/${XPDF_FOLDER}/bin64"
		cmdStr="export PATH=${pathRef}:\$PATH"
		executeCmd "$cmdStr" 0
		if [ -f ~/.bashrc ]; then
			echo "${cmdStr}" | tee --append ~/.bashrc
		fi
	fi

}

# MongoDB Info
DB_VERSION="3.6.4"
DB_PACKAGE_PREFIX_CENT6="mongodb-linux-x86_64-rhel62-$DB_VERSION"
DB_PACKAGE_CENT6="$DB_PACKAGE_PREFIX_CENT6.tgz"
DB_PACKAGE_PREFIX_CENT7="mongodb-linux-x86_64-rhel70-$DB_VERSION"
DB_PACKAGE_CENT7="$DB_PACKAGE_PREFIX_CENT7.tgz"
DB_PACKAGE_PREFIX_UB14="mongodb-linux-x86_64-ubuntu1404-$DB_VERSION"
DB_PACKAGE_UB14="$DB_PACKAGE_PREFIX_UB14.tgz"
DB_PACKAGE_PREFIX_UB16="mongodb-linux-x86_64-ubuntu1604-$DB_VERSION"
DB_PACKAGE_UB16="$DB_PACKAGE_PREFIX_UB16.tgz"
DB_FOLDER="mongodb-$DB_VERSION"
DB_URL_CENT6="https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-rhel62-$DB_VERSION.tgz"
DB_URL_CENT6_SHARE="http://download.ydstatic.com/baichuan/mongodb-linux-x86_64-rhel62-$DB_VERSION.tgz"
DB_URL_CENT7="https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-rhel70-$DB_VERSION.tgz"
DB_URL_CENT7_SHARE="http://download.ydstatic.com/baichuan/mongodb-linux-x86_64-rhel70-$DB_VERSION.tgz"
DB_URL_UB14="https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-ubuntu1404-$DB_VERSION.tgz"
DB_URL_UB14_SHARE="http://download.ydstatic.com/baichuan/mongodb-linux-x86_64-ubuntu1404-$DB_VERSION.tgz"
DB_URL_UB16="https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-ubuntu1604-$DB_VERSION.tgz"
DB_URL_UB16_SHARE="http://download.ydstatic.com/baichuan/mongodb-linux-x86_64-ubuntu1604-$DB_VERSION.tgz"

# Elastic Search Info
ES_VERSION="6.2.2"
ES_PACKAGE_PREFIX="elasticsearch-$ES_VERSION"
ES_PACKAGE="$ES_PACKAGE_PREFIX.tar.gz"
ES_PLUGIN_PACKAGE="elasticsearch-analysis-ik-$ES_VERSION.zip"
ES_URL="https://artifacts.elastic.co/downloads/elasticsearch/$ES_PACKAGE"
ES_URL_SHARE="http://download.ydstatic.com/baichuan/$ES_PACKAGE"
ES_PLUGIN_URL="https://github.com/medcl/elasticsearch-analysis-ik/releases/download/v$ES_VERSION/elasticsearch-analysis-ik-$ES_VERSION.zip"
ES_PLUGIN_URL_SHARE="http://download.ydstatic.com/baichuan/elasticsearch-analysis-ik-$ES_VERSION.zip"

# Nodejs Info
NODE_VERSION="v8.9.4"
NODE_PACKAGE_PREFIX="node-$NODE_VERSION-linux-x64"
NODE_PACKAGE="$NODE_PACKAGE_PREFIX.tar.gz"
NODE_FOLDER="node-$NODE_VERSION"
NODE_URL="https://nodejs.org/dist/$NODE_VERSION/$NODE_PACKAGE"
NODE_URL_TAOBAO="https://npm.taobao.org/mirrors/node/latest-v8.x/$NODE_PACKAGE"
NODE_URL_SHARE="http://download.ydstatic.com/baichuan/$NODE_PACKAGE"

# JAVA 依赖
JAVA_PACKAGE="openjdk-8u40-b25-linux-x64-10_feb_2015.tar.gz"
JAVA_FOLDER="java-se-8u40-ri"
JAVA_YUM_NAME="java-1.8.0-openjdk"
JAVA_APT_NAME="openjdk-8-jdk"
JAVA_URL="https://download.java.net/openjdk/jdk8u40/ri/$JAVA_PACKAGE"
JAVA_URL_SHARE="http://download.ydstatic.com/baichuan/$JAVA_PACKAGE"

# antiword-0.37 依赖
ANTIWORD_PACKAGE_CENTOS6="antiword-0.37-17.el6.x86_64.rpm"
ANTIWORD_URL_CENTOS6="http://dl.fedoraproject.org/pub/epel/6/x86_64/Packages/a/${ANTIWORD_PACKAGE_CENTOS6}"
ANTIWORD_URL_CENTOS6_SHARE="http://download.ydstatic.com/baichuan/${ANTIWORD_PACKAGE_CENTOS6}"
ANTIWORD_PACKAGE_CENTOS7="antiword-0.37-9.el7.x86_64.rpm"
ANTIWORD_URL_CENTOS7="https://forensics.cert.org/centos/cert/7/x86_64/${ANTIWORD_PACKAGE_CENTOS7}"
ANTIWORD_URL_CENTOS7_SHARE="http://download.ydstatic.com/baichuan/${ANTIWORD_PACKAGE_CENTOS7}"

# xpdf-tools-linux-4.00 依赖
XPDF_FOLDER="xpdf-tools-linux-4.00"
XPDF_PACKAGE="${XPDF_FOLDER}.tar.gz"
XPDF_URL="https://xpdfreader-dl.s3.amazonaws.com/${XPDF_PACKAGE}"
XPDF_URL_SHARE="http://download.ydstatic.com/baichuan/${XPDF_PACKAGE}"

# 其它
MANUAL_HELP_URL="http://noteyoudao.udesk.cn/hc/articles/61245"

# 百川Info
BAICHUAN_VERSION="v1.1"

# 脚本参数
ONLY_START=0
ONLY_STOP=0
PRINT_HELP=0
OFFICIAL_DOWNLOAD=0
IS_DEBUG=0
# this is test param, not support to use for customers
CLEAN_ENV=0

# 脚本使用的其它全局变量
CENT6="CENT6"
CENT7="CENT7"
UB14="UB14"
UB16="UB16"
OS_VERSION=""
ROOT_FOLDER=$(pwd)
IS_CENTOS=0
IS_UBUNTU=0
IS_SUDOER=0
IS_PORT_OPENED=0
PM2_INST_NAME="pm2_baichuan"
APP_NAME="云协作Lite"
IS_INSTALL=0
CODE_SUCCESS=0
CODE_FAILURE=1
CODE_OTHER=9

if [ ! -f "$ROOT_FOLDER/oneboxInstaller.sh" ]; then
	printError "请在安装脚本所在目录执行此脚本"
	exitFromScript ${CODE_OTHER}
fi

######################################
# 解析命令行参数
#
while true; do
	case "$1" in
		--h | --help | -h | -help)
			PRINT_HELP=1
			shift 1
			;;
		--official | -official)
			OFFICIAL_DOWNLOAD=1
			shift 1
			;;
		--debug | -debug)
			IS_DEBUG=1
			shift 1
			;;
		--cleanEnv | -cleanEnv)
			CLEAN_ENV=1
			shift 1
			;;
		--onlyStart | -onlyStart)
			ONLY_START=1
			shift 1
			;;
		--onlyStop | -onlyStop)
			ONLY_STOP=1
			shift 1
			;;
		--version | -version)
			BAICHUAN_VERSION="$2"
			shift 2
			;;
		*)
			if [ -z "$1" ]; then
				break
			else
				printWarn "unsupported param:$1"
				printWarn "请用 --h 参数，查看脚本的使用方法"
				exitFromScript ${CODE_FAILURE}
			fi
			;;
	esac
done
# get the baichuan info according the param of --verison
BAICHUAN_FOLDER="baichuan-${BAICHUAN_VERSION}"
BAICHUAN_PACKAGE="${BAICHUAN_FOLDER}.zip"

BAICHUAN_URL="http://download.ydstatic.com/baichuan/$BAICHUAN_PACKAGE"
if [ "$ONLY_START" -eq 0 ] && [ "$ONLY_STOP" -eq 0 ]; then
	IS_INSTALL=1
fi

######################################
# 运行环境监测：包括OS, JDK 8等等
#
# 检测系统版本
checkOSVersion
if [ "$PRINT_HELP" -eq 1 ]; then
	# 此函数依赖checkOSVersion的结果
	printHelp
	exitFromScript ${CODE_OTHER}
fi

if [ "$CLEAN_ENV" -eq 1 ]; then
	cleanEnv
	exitFromScript ${CODE_OTHER}
fi
# 检测当前目录是否已经安装了百川
if [ -d "$BAICHUAN_FOLDER" ] && [ "$IS_INSTALL" -eq 1 ]; then
	read -r -p "此文件夹已经安装了 $APP_NAME 。是否要重新安装（y/n）: " YorN
	if [ "$YorN" != "y" ] && [ "$YorN" != "Y" ]; then
		printInfo "如果想重新启动或停掉服务，请指定 --onlyStart 或 --onlyStop 参数"
		exitFromScript ${CODE_OTHER}
	fi
fi

#检测内存，需要大于4G和CPU，需要64bit
if [ "$IS_DEBUG" -eq 0 ] && [ "$IS_INSTALL" -eq 1 ]; then
	checkCpuBit
	is64Bit=$?
	if [ "${is64Bit}" -eq 0 ]; then
		printError "需要64位系统"
		exitFromScript ${CODE_OTHER}
	fi
	if [ -f /proc/meminfo ]; then
		totalMem=$(grep MemTotal /proc/meminfo | awk '{print $2}')
	fi

	if [ "$totalMem" == "" ]; then
		printWarn "获取内存信息失败"
		read -r -p "请确认本机内存大于4G，否则启动 $APP_NAME 可能失败（y/n）: " YorN
		if [ "$YorN" != "y" ] && [ "$YorN" != "Y" ]; then
			printInfo "请选择内存大于4G的环境运行 $APP_NAME"
			exitFromScript ${CODE_OTHER}
		fi
	elif [ "$totalMem" -le 3000000 ]; then
		printError "$APP_NAME 需要最小4G的内存空间。当前内存 $totalMem KB"
		exitFromScript ${CODE_OTHER}
	fi
fi

printStep "检测当前用户以及 '${APP_NAME}' 的系统依赖组件 ..."
# 检测当前是否为Root
# 此函数依赖checkOSVersion方法的执行
checkRoot

# 检测unzip
if [ "$IS_INSTALL" -eq 1 ] && ! command -v unzip >/dev/null 2>&1; then
	checkSudoer "unzip"
	printWarn "开始在线安装unzip命令，请确保连接internet正常，安装过程中，可能需要输入当前账户的密码"
	if [ "$IS_CENTOS" -eq 1 ]; then
		cmdStr="sudo yum -y install unzip"
		sudo yum -y install unzip
	else
		cmdStr="sudo apt-get install unzip"
		sudo apt-get -y install unzip
	fi
	if ! command -v unzip >/dev/null 2>&1; then
		printError "安装unzip失败。请运行此命令，尝试手动安装：$cmdStr"
		exitFromScript ${CODE_FAILURE}
	fi
fi

# 检测python2命令
if [ "$IS_INSTALL" -eq 1 ] && ! command -v python2 >/dev/null 2>&1; then
	checkSudoer "python2"
	printWarn "开始在线安装python2，请确保连接internet正常，安装过程中，可能需要输入当前账户的密码"
	if [ "$IS_CENTOS" -eq 1 ]; then
		cmdStr="sudo yum -y install python"
		sudo yum -y install python
	else
		cmdStr="sudo apt-get install python"
		sudo apt-get -y install python
	fi
	if ! command -v python >/dev/null 2>&1; then
		printError "安装python失败。请运行此命令，尝试手动安装：$cmdStr"
		exitFromScript ${CODE_FAILURE}
	fi
fi

# 检测make命令
if [ "$IS_INSTALL" -eq 1 ] && ! command -v make >/dev/null 2>&1; then
	checkSudoer "make"
	printWarn "开始在线安装make，请确保连接internet正常，安装过程中，可能需要输入当前账户的密码"
	if [ "$IS_CENTOS" -eq 1 ]; then
		cmdStr="sudo yum -y install make"
		sudo yum -y install make
	else
		cmdStr="sudo apt-get install make"
		sudo apt-get -y install make
	fi
	if ! command -v make >/dev/null 2>&1; then
		printError "安装make失败。请运行此命令，尝试手动安装：$cmdStr"
		exitFromScript ${CODE_FAILURE}
	fi
fi
# 检测wget命令
if ! command -v wget >/dev/null 2>&1; then
	checkSudoer 'wget'
	printWarn "开始在线安装wget，请确保连接internet正常，安装过程中，可能需要输入当前账户的密码"
	# 安装wget依赖
	if [ "$IS_CENTOS" -eq 1 ]; then
		sudo yum -y install wget
	else
		sudo apt-get -y install wget
	fi
fi
if ! command -v wget >/dev/null 2>&1; then
	printError "安装wget失败"
	exitFromScript ${CODE_FAILURE}
fi

# 检测JDK 8
# 安装顺序：
# 1，如果本地已有安装包，则直接安装
# 2，如果本地没有安装包，则尝试下载安装（分别尝试百川共享和在线官网）
# 3，如果下载失败但有Root权限，则尝试安装工具(yum/apt)安装
# 4，如果下载失败且没有Root权限，提示安装失败
isJavaReady=0
printStep "检测Java OpenJDK(1.8或以上)组件 ..."
# 首先检测本地是否已经安装
if [ -f "$ROOT_FOLDER/$JAVA_FOLDER/bin/java" ]; then
	isJavaReady=1
fi

# 其次检测是否系统已经安装满足要求的JAVA
if [ "$isJavaReady" -eq 0 ] && command -v java >/dev/null 2>&1; then
	checkJAVAVersion
	isJavaReady=$?
fi
if [ "$isJavaReady" -eq 0 ] && ([ "$ONLY_START" -eq 1 ] || [ "$ONLY_STOP" -eq 1 ]); then
	printError "JAVA(1.8或以上)依赖没有安装，无法启动或停止服务"
	exitFromScript ${CODE_FAILURE}
fi
if [ "$isJavaReady" -eq 0 ]; then
	printStep "安装JAVA OpenJDK（1.8）"
fi

# 再次检测是否可以本地安装（i.e. 本地已经有了安装包）
if [ "$isJavaReady" -eq 0 ] && [ -f "${ROOT_FOLDER}/${JAVA_PACKAGE}" ]; then
	printInfo "解压安装"
	installJAVALocally
	if [ "$?" -eq 0 ]; then
		isJavaReady=1
	else
		rm -rf "${ROOT_FOLDER}/${JAVA_PACKAGE}"
	fi
fi

# 然后检测是否可以下载安装
if [ "$isJavaReady" -eq 0 ]; then
	# 先从百川共享下载
	if [ "$OFFICIAL_DOWNLOAD" -eq 0 ]; then
		download "$JAVA_URL_SHARE" "$JAVA_PACKAGE" 1
	fi
	if [ ! -f "${ROOT_FOLDER}/${JAVA_PACKAGE}" ]; then
		# 如果百川共享下载失败，尝试官方下载
		download "$JAVA_URL" "$JAVA_PACKAGE" 1
	fi
	if [ -f "${ROOT_FOLDER}/${JAVA_PACKAGE}" ]; then
		# 下载成功，则解压安装
		installJAVALocally
		if [ "$?" -eq 0 ]; then
			isJavaReady=1
		else
			rm -rf "${ROOT_FOLDER}/${JAVA_PACKAGE}"
		fi
	fi
fi

# 然后检测是否可以在线安装，具有Root权限的可以在线安装
if [ "$isJavaReady" -eq 0 ]; then
	checkSudoer 'JAVA' 1
	if [ "$IS_SUDOER" -eq 1 ]; then
		# 如果用户有Root权限，则通过包管理工具安装
		printInfo "利用安装工具，在线安装"
		if [ "$IS_CENTOS" -eq 1 ]; then
			sudo yum -y install $JAVA_YUM_NAME
		elif [ "$IS_UBUNTU" -eq 1 ]; then
			sudo add-apt-repository -y ppa:openjdk-r/ppa
			sudo apt-get -y update
			sudo apt-get -y install $JAVA_APT_NAME
		fi
		checkJAVAVersion
		isJavaReady=$?
	fi
fi

# 如果本地安装了JAVA，需要设置JAVA_HOME全局变量
if [ -f "${ROOT_FOLDER}/${JAVA_FOLDER}/bin/java" ]; then
	cmdStr="export JAVA_HOME=${ROOT_FOLDER}/${JAVA_FOLDER}"
	executeCmd "$cmdStr" 0
fi
if [ "$isJavaReady" -eq 0 ]; then
	printError "安装Open JDK 8失败。"
	printWarn "请参考帮助文档（ ${MANUAL_HELP_URL} ）中的'安装前的准备工作'，手动安装，之后重新运行此脚本。"
	exitFromScript ${CODE_FAILURE}
fi

# 检测nodejs依赖
# 安装顺序：
# 1，如果本地已有安装包，则直接安装
# 2，如果本地没有安装包，则尝试下载安装（分别尝试百川共享和在线官网）
# 4，如果下载失败，提示安装失败
isNodeReady=0
printStep "检测Nodjs(8.X或以上)组件 ..."
# 首先本地是否已经安装
if [ -f "${ROOT_FOLDER}/${NODE_FOLDER}/bin/node" ]; then
	isNodeReady=1
fi
# 其次检测系统自带nodejs
if [ "$isNodeReady" -eq 0 ] && command -v node >/dev/null 2>&1; then
	checkNodejsVersion
	isNodeReady=$?
fi
if [ "$isNodeReady" -eq 0 ] && ([ "$ONLY_START" -eq 1 ] || [ "$ONLY_STOP" -eq 1 ]); then
	printError "Nodjs(8.X或以上)依赖没有安装，无法启动或停止服务"
	exitFromScript ${CODE_FAILURE}
fi
# 再次检测是否可以本地安装，i.e. 本地已经有了安装包
if [ "$isNodeReady" -eq 0 ] && [ -f "${ROOT_FOLDER}/${NODE_PACKAGE}" ]; then
	printInfo "解压安装"
	installNodeLocally
	if [ "$?" -eq 0 ]; then
		isNodeReady=1
	else
		rm -rf "${ROOT_FOLDER}/${NODE_PACKAGE}"
	fi
fi

# 然后检测是否可以下载安装
if [ "$isNodeReady" -eq 0 ]; then
	# 没有有效的node命令，并且本地没有安装包，尝试下载安装
	if [ "$OFFICIAL_DOWNLOAD" -eq 0 ]; then
		download "$NODE_URL_SHARE" "$NODE_PACKAGE" 1
		if [ ! -f "${ROOT_FOLDER}/${NODE_PACKAGE}" ]; then
			download "$NODE_URL_TAOBAO" "$NODE_PACKAGE" 1
		fi
	fi
	if [ ! -f "${ROOT_FOLDER}/${NODE_PACKAGE}" ]; then
		download "$NODE_URL" "$NODE_PACKAGE" 1
	fi

	if [ -f "${ROOT_FOLDER}/${NODE_PACKAGE}" ]; then
		installNodeLocally
		isNodeReady=1
		if [ "$?" -eq 0 ]; then
			isNodeReady=1
		else
			rm -rf "${ROOT_FOLDER}/${NODE_PACKAGE}"
		fi
	fi
fi
if ! command -v node >/dev/null 2>&1 && [ -f "${ROOT_FOLDER}/${NODE_FOLDER}/bin/node" ]; then
	cmdStr="export PATH=${ROOT_FOLDER}/${NODE_FOLDER}/bin:\$PATH"
	executeCmd "$cmdStr" 0
	if [ -f ~/.bashrc ] && [ ${IS_INSTALL} -eq 1 ]; then
		echo "${cmdStr}" | tee --append ~/.bashrc
	fi
	checkNodejsVersion
	isNodeReady=$?
fi
if [ "$isNodeReady" -eq 0 ]; then
	printError "安装Nodejs失败。"
	printWarn "请参考帮助文档（ ${MANUAL_HELP_URL} ）中的'安装Nodejs'，手动安装，之后重新运行此脚本。"
	exitFromScript ${CODE_FAILURE}
fi
######################################
# 安装启动数据库
#
isDBReady=0
printStep "检测Mongodb的安装和启动 ..."
# 首先检测本地是否已经安装
if [ -f "${ROOT_FOLDER}/${DB_FOLDER}/bin/mongod" ]; then
	if [ "$ONLY_STOP" -eq 1 ]; then
		stopDB
	else
		startDB 1
	fi
	isDBReady=1
fi
# 其次检测系统已安装的mongod
if [ "$isDBReady" -eq 0 ] && command -v mongod >/dev/null 2>&1; then
	rawVersion=$(mongod --version)
	echo "$rawVersion" | grep v3.6 && isDBReady=1
	if [ "$isDBReady" -eq 0 ]; then
		printWarn "系统已安装mongod版本过低：${rawVersion}"
	else
		printInfo "检测到已安装的全局mongod命令"
		if [ "$ONLY_STOP" -eq 1 ]; then
			stopDB
		else
			startDB 0
		fi
		isDBReady=1
	fi
fi
if [ "$isDBReady" -eq 0 ]; then
	if [ "$ONLY_START" -eq 1 ] || [ "$ONLY_STOP" -eq 1 ]; then
		printError "Mongodb(3.6.X)依赖没有安装，无法启动或启动服务"
		exitFromScript ${CODE_FAILURE}
	fi
	installMongodb
fi

######################################
# 安装启动ES
#
isESReady=0
printStep "检测ElasticSearch及其插件的安装与启动"
# 首先检测本地是否已经安装
if [ -f "${ROOT_FOLDER}/${ES_PACKAGE_PREFIX}/bin/elasticsearch" ]; then
	if [ "$ONLY_STOP" -eq 1 ]; then
		stopES
	else
		startES
	fi
	isESReady=1
fi
if [ "$isESReady" -eq 0 ] && ([ "$ONLY_START" -eq 1 ] || [ "$ONLY_STOP" -eq 1 ]); then
	printError "ElasticSearch依赖没有安装，无法启动或停止服务"
	exitFromScript ${CODE_FAILURE}
fi
# 其次检测本地是否有安装包
if [ "$isESReady" -eq 0 ] && [ -f "${ROOT_FOLDER}/${ES_PACKAGE}" ]; then
	installESLocally
	isESReady=1
fi
# 再次检测是否可以下载安装
if [ "$isESReady" -eq 0 ]; then
	if [ "$OFFICIAL_DOWNLOAD" -eq 0 ]; then
		download "$ES_URL_SHARE" "$ES_PACKAGE" 1
	fi
	if [ ! -f "${ROOT_FOLDER}/${ES_PACKAGE}" ]; then
		download "$ES_URL" "$ES_PLUGIN_PACKAGE"
	fi
	if [ ! -f "${ROOT_FOLDER}/${ES_PLUGIN_PACKAGE}" ]; then
		download "$ES_PLUGIN_URL_SHARE" "$ES_PLUGIN_PACKAGE" 1
	fi
	if [ ! -f "${ROOT_FOLDER}/${ES_PLUGIN_PACKAGE}" ]; then
		download "$ES_PLUGIN_URL" "$ES_PLUGIN_PACKAGE"
	fi
	installESLocally
	isESReady=1
fi

######################################
# 安装doc extract相关依赖
#
if [ ${IS_INSTALL} -eq 1 ]; then
	printStep "检测附件解压依赖组件"
	installFileExtractTools
fi
#####################################
# 打开8081端口的防火墙
#
if [ "$IS_INSTALL" -eq 1 ]; then
	checkSudoer "firewall" 1
	if [ "$IS_SUDOER" -eq 1 ]; then
		if [ "$OS_VERSION" == "$CENT7" ]; then
			printWarn "尝试打开防火墙的8081端口，此操作需要验证当前用户是否有Root的权限，可能需要输入当前账号的密码"
			zones=$(firewall-cmd --get-active-zones)
			if echo "$zones" | grep -E "^public$"; then
				sudo firewall-cmd --zone=public --add-port=8081/tcp --permanent >/dev/null 2>&1 && IS_PORT_OPENED=1
				sudo firewall-cmd --reload && IS_PORT_OPENED=1
			else
				printWarn "没有发现默认的域：public。需要安装后客户手动打开防火墙端口"
			fi
		elif [ "$OS_VERSION" == "$CENT6" ]; then
			printWarn "尝试打开防火墙的8081端口，此操作需要验证当前用户是否有Root的权限，可能需要输入当前账号的密码"
			sudo iptables -I INPUT -p tcp -m tcp --dport 8081 -j ACCEPT && IS_PORT_OPENED=1 || IS_PORT_OPENED=0
			sudo service iptables save && IS_PORT_OPENED=1 || IS_PORT_OPENED=0
		elif [ "$OS_VERSION" == "$UB16" ] || [ "$OS_VERSION" == "$UB14" ]; then
			printWarn "尝试打开防火墙的8081端口，此操作需要验证当前用户是否有Root的权限，可能需要输入当前账号的密码"
			sudo iptables -I INPUT -p tcp -m tcp --dport 8081 -j ACCEPT && IS_PORT_OPENED=1 || IS_PORT_OPENED=0
		fi
	else
		printWarn "当前用户没有Root权限，无法自动在防火墙中打开端口8081。"
	fi
fi

#####################################
# 安装启动百川
#
# 检测是否有已有的百川在运行
checkProcess "$PM2_INST_NAME"
BAICHUAN_RUNNING=$?
if [ "$BAICHUAN_RUNNING" -eq 1 ]; then
	if [ "$ONLY_START" -eq 1 ]; then
		printSuccess "$APP_NAME 正在运行"
		exitFromScript ${CODE_SUCCESS}
	fi
	printWarn "关闭正在运行的 $APP_NAME"
	kill $(ps -ef | grep "$PM2_INST_NAME" | grep -v "grep" | awk '{print $2}')
	sleep 5
	checkProcess "$PM2_INST_NAME"
	BAICHUAN_RUNNING=$?
	if [ "$BAICHUAN_RUNNING" -eq 1 ]; then
		printError "关闭正在运行的 $APP_NAME 失败"
		ps -ef | grep "$PM2_INST_NAME"
		exitFromScript ${CODE_FAILURE}
	fi
fi
if [ "$IS_INSTALL" -eq 1 ]; then
	printStep "安装 $APP_NAME ($BAICHUAN_PACKAGE)"
	if [ -d "$BAICHUAN_FOLDER" ]; then
		printWarn "删除已经存在的 $APP_NAME 文件夹：$BAICHUAN_FOLDER"
		rm -rf "$BAICHUAN_FOLDER"
	fi
	if [ ! -f "${ROOT_FOLDER}/${BAICHUAN_PACKAGE}" ]; then
		download "$BAICHUAN_URL" "$BAICHUAN_PACKAGE"
	fi

	cmdStr="unzip $BAICHUAN_PACKAGE -d $BAICHUAN_FOLDER"
	executeCmd "$cmdStr" 0
	if [ ! -f "${ROOT_FOLDER}/${BAICHUAN_FOLDER}/client/admin/index.html" ]; then
		printError "$APP_NAME 有文件缺失，请确认下载正确的安装包"
		exitFromScript ${CODE_FAILURE}
	fi
	if ! cd "$BAICHUAN_FOLDER"; then
		printError "进入百川工程目录失败"
		exitFromScript ${CODE_FAILURE}
	fi
	if [ ! -f "${ROOT_FOLDER}/${BAICHUAN_FOLDER}/node_modules/pm2/bin/pm2" ]; then
		printStep "安装 $APP_NAME NPM依赖包"
		if [ $OFFICIAL_DOWNLOAD -eq 0 ]; then
			npm install --registry https://registry.npm.taobao.org --production --no-optional --silent
		else
			npm install --production --no-optional --silent
		fi
	fi
	if [ ! -f "${ROOT_FOLDER}/${BAICHUAN_FOLDER}/node_modules/pm2/bin/pm2" ]; then
		printError "NPM依赖安装失败"
		exitFromScript ${CODE_FAILURE}
	fi
	# 首先检测是否自动安装的数据库
	if [ -f "${ROOT_FOLDER}/${DB_FOLDER}/bin/mongod" ]; then
		printStep "检测数据库是否需要升级"
		node updateData.js
	fi

fi
if [ ${IS_INSTALL} -eq 1 ] || [ ${ONLY_START} -eq 1 ]; then
	printStep "启动 $APP_NAME ..."
	if [ ${ONLY_START} -eq 1 ] && ! cd "$BAICHUAN_FOLDER"; then
		printError "进入百川工程目录失败"
		exitFromScript ${CODE_FAILURE}
	fi
	if [ "$IS_CENTOS" -eq 1 ]; then
		cmdStr="sh"
	else
		cmdStr="/bin/bash"
	fi
	$cmdStr pm2Manager.sh --start

	printSuccess "安装启动完毕。"
	if [ ${IS_INSTALL} -eq 1 ] && [ "${IS_PORT_OPENED}" -eq 0 ]; then
		printWarn "后续配置工作：根据此链接文档（ $MANUAL_HELP_URL ）中关于‘打开防火墙端口’中的描述，打开8081端口，使外部可以访问。"
	fi
	cd "$ROOT_FOLDER"
fi
exitFromScript ${CODE_SUCCESS}
