#!/bin/bash

###############################################################################
# 构建 tnb 应用
###############################################################################

set -e

proj_dir='~/Downloads/tnb'

###############################################################################
# 构建依赖
###############################################################################
build_dependencies() {
  cd ${proj_dir}
  git clone https://git.reghao.cn/reghao/jutil
  cd jutil
  mvn clean install -Dmaven.test.skip=true
  
  cd ${proj_dir}
  git clone https://git.reghao.cn/reghao/oss
  cd oss
  mvn clean install -Dmaven.test.skip=true -pl oss/oss-sdk
}

###############################################################################
# 构建 tnb 应用 jar 包
###############################################################################
build_jar() {
  cd ${proj_dir}
  mvn clean package -Dmaven.test.skip
}

###############################################################################
# 运行 tnb 应用
###############################################################################
exec_jar() {
  nohup java -jar ${proj_dir}/gateway/target/tnb-gateway.jar > tnb-gateway.log 2>&1 &
  nohup java -jar ${proj_dir}/account/account-service/target/tnb-account.jar > tnb-account.log 2>&1 &
  nohup java -jar ${proj_dir}/user/user-service/target/tnb-user.jar > tnb-user.log 2>&1 &
  nohup java -jar ${proj_dir}/message/message-service/target/tnb-message.jar > tnb-message.log 2>&1 &
  nohup java -jar ${proj_dir}/file/file-service/target/tnb-file.jar > tnb-file.log 2>&1 &
  nohup java -jar ${proj_dir}/content/content-service/target/tnb-content.jar > tnb-content.log 2>&1 &
  nohup java -jar ${proj_dir}/data/data-service/target/tnb-data.jar > tnb-data.log 2>&1 &
  nohup java -jar ${proj_dir}/search/search-service/target/tnb-search.jar > tnb-search.log 2>&1 &
}

###############################################################################
# 构建 tnb 应用镜像
###############################################################################
build_image() {
  commit_id=`git rev-parse HEAD | cut -c 1-8`
  docker_prefix='tnb'
  cd ${proj_dir}/tnb/gateway/
  docker build -t ${docker_prefix}/gateway:${commit_id} .
  
  cd ${proj_dir}/tnb/account/account-service/
  docker build -t ${docker_prefix}/account:${commit_id} .
  
  cd ${proj_dir}/tnb/user/user-service/
  docker build -t ${docker_prefix}/user:${commit_id} .
  
  cd ${proj_dir}/tnb/message/message-service/
  docker build -t ${docker_prefix}/message:${commit_id} .
  
  cd ${proj_dir}/tnb/content/content-service/
  docker build -t ${docker_prefix}/content:${commit_id} .
  
  cd ${proj_dir}/tnb/file/
  docker build -t ${docker_prefix}/file:${commit_id} .
}

exec_image() {
  echo "not implement..."
}

echo "构建第三方依赖..."
build_dependencies

echo "构建 tnb jar 应用..."
build_jar

echo "运行 tnb jar 应用..."
exec_jar
