#!/bin/bash

echo "start to install young agent..."

youngAgentWorkDir="/usr/local/young/agent"
youngAgentWorkDirBak="${youngAgentWorkDir}_bak"
youngAgentModuleDir="${youngAgentWorkDir}/.module"
youngAgentEnvFile="/etc/young_env"
youngAgentLogDir="/var/log/young/agent"

#首先把当前young_agent程序停止
echo "remove young agent server if exists ..."
systemctl stop young_agent.service
systemctl disable young_agent.service

# 判断young_agent运行目录是否存在
if [ -d "${youngAgentWorkDir}" ]; then
  # 当前young_agent目录存在，进行备份
  if [ -d "${youngAgentWorkDirBak}" ]; then
    # young_agent备份目录存在,先删除
    echo "back up dir ${youngAgentWorkDirBak} exists, rm -rf ${youngAgentWorkDirBak}"
    rm -rf ${youngAgentWorkDirBak}
  fi

  echo "back up ${youngAgentWorkDir} to ${youngAgentWorkDirBak}"
  mv ${youngAgentWorkDir} ${youngAgentWorkDirBak}
fi

mkdir -p "${youngAgentWorkDir}"
echo "${youngAgentWorkDir} created."

# 赋予权限
chmod 755 "${youngAgentWorkDir}"
echo "set mod of ${youngAgentWorkDir} to 755."

if [ -f "${youngAgentEnvFile}" ]; then
  echo "remove file ${youngAgentEnvFile}"
  rm -rf ${youngAgentEnvFile}
fi

touch ${youngAgentEnvFile}
echo "AGENT_ID=default" >> ${youngAgentEnvFile}
echo "LOG_DIR=${youngAgentLogDir}" >> ${youngAgentEnvFile}

cp -rp /root/cdninstall/pkg/young_agent/* ${youngAgentWorkDir}

mkdir -p ${youngAgentModuleDir}/bash/bin
cp -rf /bin/bash ${youngAgentModuleDir}/bash/bin

if [ ! -d "${youngAgentLogDir}" ]; then
    mkdir -p ${youngAgentLogDir}
fi

if [ -f "${youngAgentLogDir}/young-agent.log" ]; then
  mv ${youngAgentLogDir}/young-agent.log ${youngAgentLogDir}/young-agent.log_bak
fi

echo "Enable and start young_agent.service"
systemctl enable ${youngAgentWorkDir}/run/young_agent.service
systemctl start young_agent.service

echo "检查 young agent 安装状态..."

# 简单地检查服务是否在运行
sleep 3
if systemctl is-active --quiet young_agent.service; then
    echo ">>> young agent 服务已成功启动 <<<"
else
    echo ">>> young agent 服务启动失败 <<<"
    echo "查看服务状态:"
    systemctl status young_agent.service --no-pager
    
    if [ -f ${youngAgentLogDir}/young-agent.log ]; then
        echo "日志内容:"
        tail ${youngAgentLogDir}/young-agent.log
    fi
    
    exit 2
fi

echo ""
echo ""
echo "the log tail is: "
tail ${youngAgentLogDir}/young-agent.log
echo ""
echo ">>> young agent install success <<<"

