#!/bin/bash
##################################################################
# Filename: BuildSystemd.sh
# Function: Build GBaseService_${servername}.service and add to systemd
# Write by: liaosnet@gbasedbt.com
# Version : 1.4.15
##################################################################
##### Defind env
export LANG=C
_loginfo(){
  echo -e "[$(date +'%F %T')] $*"
}

if [ ! x"$(whoami)" = "xroot" ]; then
  _loginfo "MUST root user to run!"
  exit 1
fi

id gbasedbt >/dev/null 2>&1
if [ ! $? -eq 0 ]; then
  _loginfo "USER gbasedbt not found!"
  exit 1
fi

if [ ! -f /GBASEDBTTMP/.infxdirs ]; then
  _loginfo ".infxdirs not found!"
  exit 1
fi
GBASEDIR=$(awk '{print $1; exit}' /GBASEDBTTMP/.infxdirs)

# build env_file
GBASEENV=$(su - gbasedbt -c "env | egrep '(GBASEDBT|ONCONFIG|PATH|DB_LOCALE|CLIENT_LOCALE|GL_|DBDATE|LD_LIBRARY_PATH)'")
GBASESERVER=$(echo "${GBASEENV}" | awk -F'=' '/GBASEDBTSERVER/{print $2}')
if [ x"${GBASESERVER}" = x ]; then
  _loginfo "Servername not found!"
  exit 1
fi

# 
if [ -f /usr/lib/systemd/system/GBaseService_${GBASESERVER}.service ]; then
  _loginfo "GBaseService_${GBASESERVER}.service is exists! Please delete it."
  exit 1
fi

# build systemd
_loginfo "Build GBaseService_${GBASESERVER}.service file."
cat <<EOF > GBaseService_${GBASESERVER}.service
# /usr/lib/systemd/system/GBaseService_${GBASESERVER}.service
# 注：以下中文注释用于理解
[Unit]
# Wants：需要的服务
# After：在指定的服务正常启动后才会启动
Description=GBase 8s Database Server
Documentation=file:${GBASEDIR}/release/en_us/0333
Wants=network-online.target
After=network.target network-online.target
  
[Service]
# Type：oneshot只有在该服务的主服务进程退出之后，systemd 才会认为该服务启动完成，才会开始启动后继单元。
#       forking守护进程(服务)在启动时会转入后台运行
# User：使用启动的用户
# Group：使用启动的用户组
# EnvironmentFile：使用的环境变量文件，以Key=Value的方式存储，需要注意的是 '$' 变量不扩展
# ExecStart：启动命令，需要绝对路径
# ExecStop：关闭命令，需要绝对路径
# TimeoutSec：服务启动/关闭超时时长，默认的DefaultTimeoutStartSec/DefaultTimeoutStopSec值为90秒
# Restart：always 只要不是通过systemctl stop来停止服务，任何情况下都必须要重启服务
# RestartSec：systemctl检测到异常，重启等待时长，单位是秒
Type=forking
User=gbasedbt
Group=gbasedbt
RemainAfterExit=yes
EOF

echo "${GBASEENV}" | awk '{print "Environment=\042"$0"\042"}' >> GBaseService_${GBASESERVER}.service

cat <<EOF >> GBaseService_${GBASESERVER}.service
ExecStart=${GBASEDIR}/bin/oninit
ExecStop=${GBASEDIR}/bin/onshutdown.sh
TimeoutSec=1800
Restart=always
RestartSec=60
  
[Install]
WantedBy=multi-user.target
EOF

# 
if [ -f ${GBASEDIR}/bin/onshutdown.sh ]; then
  sed -i "s#/ksh#/sh#g" ${GBASEDIR}/bin/onshutdown.sh
fi

# 
_loginfo "Move GBaseService_${GBASESERVER}.service to /usr/lib/systemd/system/ ."
if [ -f GBaseService_${GBASESERVER}.service ]; then
  mv GBaseService_${GBASESERVER}.service /usr/lib/systemd/system/
fi

# 加入systemd 
_loginfo "Add to systemd. If GBase 8s is Online, stop it. Then use systemctl start GBaseService_${GBASESERVER}.service ."
systemctl enable GBaseService_${GBASESERVER}.service

exit 0
