#!/usr/bin/env bash

# Copyright © 2023 OpenIM. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

set -o errexit
set +o nounset
set -o pipefail

OPENIM_ROOT=$(cd "$(dirname "${BASH_SOURCE[0]}")"/../.. && pwd -P)
[[ -z ${COMMON_SOURCED} ]] && source ${OPENIM_ROOT}/scripts/install/common.sh

readonly SERVER_NAME="openim-crontask"
readonly SERVER_PATH="${OPENIM_OUTPUT_HOSTBIN}/openim-crontask"

openim::log::status "Start OpenIM Cron, binary root: ${SERVER_NAME}"
openim::log::info "Start OpenIM Cron, path: ${SERVER_PATH}"

openim::util::stop_services_with_name ${SERVER_NAME}

sleep 1

openim::log::status "start cron_task process"

nohup ${SERVER_PATH} >>${log_file} 2>&1 &

# Check launched service process
check=`ps  | grep -w ./${cron_task_name} | grep -v grep| wc -l`
if [ $check -ge 1 ]
then
newPid=`ps  | grep -w ./${cron_task_name} | grep -v grep|awk '{print $2}'`
allPorts=""
    echo -e ${SKY_BLUE_PREFIX}"SERVICE START SUCCESS "${COLOR_SUFFIX}
    echo -e ${SKY_BLUE_PREFIX}"SERVICE_NAME: "${COLOR_SUFFIX}${BACKGROUND_GREEN}${cron_task_name}${COLOR_SUFFIX}
    echo -e ${SKY_BLUE_PREFIX}"PID: "${COLOR_SUFFIX}${BACKGROUND_GREEN}${newPid}${COLOR_SUFFIX}
    echo -e ${SKY_BLUE_PREFIX}"LISTENING_PORT: "${COLOR_SUFFIX}${BACKGROUND_GREEN}${allPorts}${COLOR_SUFFIX}
else
    echo -e ${BACKGROUND_GREEN}${cron_task_name}${COLOR_SUFFIX}${RED_PREFIX}"\n SERVICE START ERROR, PLEASE CHECK openIM.log"${COLOR_SUFFIX}
fi


# Print the necessary information after installation
function iam::pump::info() {
cat << EOF
iam-pumpn listen on: ${IAM_PUMP_HOST}
EOF
}

# 安装
function iam::pump::install()
{
  pushd ${IAM_ROOT}

  # 1. 构建 iam-pump
  make build BINS=iam-pump
  iam::common::sudo "cp ${LOCAL_OUTPUT_ROOT}/platforms/linux/amd64/iam-pump ${IAM_INSTALL_DIR}/bin"

  # 2.  生成并安装 iam-pump 的配置文件（iam-pump.yaml）
  echo ${LINUX_PASSWORD} | sudo -S bash -c \
    "./scripts/genconfig.sh ${ENV_FILE} configs/iam-pump.yaml > ${IAM_CONFIG_DIR}/iam-pump.yaml"

  # 3. 创建并安装 iam-pump systemd unit 文件
  echo ${LINUX_PASSWORD} | sudo -S bash -c \
    "./scripts/genconfig.sh ${ENV_FILE} init/iam-pump.service > /etc/systemd/system/iam-pump.service"

  # 4. 启动 iam-pump 服务
  iam::common::sudo "systemctl daemon-reload"
  iam::common::sudo "systemctl restart iam-pump"
  iam::common::sudo "systemctl enable iam-pump"
  iam::pump::status || return 1
  iam::pump::info

  iam::log::info "install iam-pump successfully"
  popd
}

# 卸载
function iam::pump::uninstall()
{
  set +o errexit
  iam::common::sudo "systemctl stop iam-pump"
  iam::common::sudo "systemctl disable iam-pump"
  iam::common::sudo "rm -f ${IAM_INSTALL_DIR}/bin/iam-pump"
  iam::common::sudo "rm -f ${IAM_CONFIG_DIR}/iam-pump.yaml"
  iam::common::sudo "rm -f /etc/systemd/system/iam-pump.service"
  set -o errexit
  iam::log::info "uninstall iam-pump successfully"
}

# 状态检查
function iam::pump::status()
{
  # 查看 iam-pump 运行状态，如果输出中包含 active (running) 字样说明 iam-pump 成功启动。
  systemctl status iam-pump|grep -q 'active' || {
    iam::log::error "iam-pump failed to start, maybe not installed properly"
    return 1
  }

  # 监听端口在配置文件中是 hardcode
  if echo | telnet 127.0.0.1 7070 2>&1|grep refused &>/dev/null;then
    iam::log::error "cannot access health check port, iam-pump maybe not startup"
    return 1
  fi
}

if [[ "$*" =~ iam::pump:: ]];then
  eval $*
fi
