#!/bin/bash

# 检查是否以root权限运行
if [ "$EUID" -ne 0 ]; then
  echo "请使用root权限运行此脚本"
  exit 1
fi

# 设置变量
SERVICE_NAME="site_total"
INSTALL_DIR="/www/server/site_total"
SERVICE_FILE="/etc/systemd/system/${SERVICE_NAME}.service"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
chown -R root:root $INSTALL_DIR

# 检查安装目录是否存在
if [ ! -d "$INSTALL_DIR" ]; then
  echo "错误: 安装目录 $INSTALL_DIR 不存在"
  exit 1
fi

# 检查可执行文件是否存在
if [ ! -f "${INSTALL_DIR}/${SERVICE_NAME}" ]; then
  echo "错误: 可执行文件 ${INSTALL_DIR}/${SERVICE_NAME} 不存在"
  exit 1
fi

# 确保可执行文件有执行权限
chmod +x "${INSTALL_DIR}/${SERVICE_NAME}"



# 复制nginx配置文件
NGINX_VHOST_PATH="/www/server/panel/vhost/nginx"
cp -f "${INSTALL_DIR}/scripts/site_log_format.conf" "${NGINX_VHOST_PATH}/0.site_total_log_format.conf"
if [ -f "${NGINX_VHOST_PATH}/0.site_total_map.conf" ];then
  rm -f "${NGINX_VHOST_PATH}/0.site_total_map.conf"
fi


# 复制apache配置文件
APACHE_CONF_DIR="/www/server/panel/vhost/apache"
cp -f "${INSTALL_DIR}/scripts/apache_log_format.conf" "${APACHE_CONF_DIR}/0.site_total_log_format.conf"
if [ -f "${APACHE_CONF_DIR}/0.site_total_cookie.conf" ];then
  rm -f "${APACHE_CONF_DIR}/0.site_total_cookie.conf"
fi

# 复制systemd服务文件
cp "${SCRIPT_DIR}/site_total.service" "$SERVICE_FILE"
if [ $? -ne 0 ]; then
  # lsattr 检查 /etc/systemd是否有i属性
  lsattr -d /etc/systemd|grep i >/dev/null 2>&1
  if [ $? -eq 0 ]; then
    echo "检测到 /etc/systemd 目录被加锁，正在解锁..."
    chattr -R -i /etc/systemd
    cp "${SCRIPT_DIR}/site_total.service" "$SERVICE_FILE"
    if [ $? -ne 0 ]; then
      echo "错误: 无法复制服务文件到 $SERVICE_FILE，即使解锁后仍然失败"
      exit 1
    fi
    chmod 644 "$SERVICE_FILE"
    systemctl daemon-reload
    systemctl enable "$SERVICE_NAME"

    # 再次加锁 /etc/systemd 目录
    chattr -R +i /etc/systemd &> /dev/null
  else
    echo "错误: 无法复制服务文件到 $SERVICE_FILE"
    exit 1
  fi
fi

# 设置正确的权限
chmod 644 "$SERVICE_FILE"


# 重新加载systemd配置
systemctl daemon-reload

# 启用并启动服务
systemctl enable "$SERVICE_NAME"
systemctl stop "$SERVICE_NAME"
systemctl start "$SERVICE_NAME"

# 检查服务状态
echo "服务安装完成，当前状态:"
sleep 2
systemctl status "$SERVICE_NAME"

echo "
使用以下命令管理服务:
启动: systemctl start $SERVICE_NAME
停止: systemctl stop $SERVICE_NAME
重启: systemctl restart $SERVICE_NAME
查看状态: systemctl status $SERVICE_NAME
查看日志: journalctl -u $SERVICE_NAME
"