#!/bin/bash

# ============================================
# 灵越智报 - Systemd 服务安装脚本
# ============================================

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

log_info() { echo -e "${GREEN}[INFO]${NC} $1"; }
log_warn() { echo -e "${YELLOW}[WARN]${NC} $1"; }
log_error() { echo -e "${RED}[ERROR]${NC} $1"; }

# 获取脚本所在目录
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SYSTEMD_DIR="${SCRIPT_DIR}/systemd"
LOG_DIR="/var/log/lingyue"

# 检查 root 权限
if [ "$EUID" -ne 0 ]; then
    log_error "请使用 root 用户运行此脚本"
    log_info "使用: sudo $0"
    exit 1
fi

# 创建日志目录
log_info "创建日志目录: ${LOG_DIR}"
mkdir -p ${LOG_DIR}
chmod 755 ${LOG_DIR}

# 复制服务文件
log_info "复制服务文件到 /etc/systemd/system/"
cp ${SYSTEMD_DIR}/lingyue-starter.service /etc/systemd/system/
cp ${SYSTEMD_DIR}/lingyue-extract.service /etc/systemd/system/
cp ${SYSTEMD_DIR}/lingyue-ner.service /etc/systemd/system/

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

# 询问是否启用服务
echo ""
echo "是否启用服务开机自启？"
echo "1) lingyue-starter (主应用，端口 18520)"
echo "2) lingyue-extract (模板服务，端口 18521)"
echo "3) lingyue-ner (NER 服务，端口 18522)"
echo ""

read -p "启用 lingyue-starter? [y/N]: " enable_starter
if [[ "$enable_starter" =~ ^[Yy]$ ]]; then
    systemctl enable lingyue-starter
    log_info "lingyue-starter 已启用开机自启"
fi

read -p "启用 lingyue-extract? [y/N]: " enable_extract
if [[ "$enable_extract" =~ ^[Yy]$ ]]; then
    systemctl enable lingyue-extract
    log_info "lingyue-extract 已启用开机自启"
fi

read -p "启用 lingyue-ner? [y/N]: " enable_ner
if [[ "$enable_ner" =~ ^[Yy]$ ]]; then
    systemctl enable lingyue-ner
    log_info "lingyue-ner 已启用开机自启"
fi

echo ""
log_info "安装完成！"
echo ""
echo "常用命令："
echo "  查看状态: systemctl status lingyue-starter"
echo "  启动服务: systemctl start lingyue-starter"
echo "  停止服务: systemctl stop lingyue-starter"
echo "  查看日志: journalctl -u lingyue-starter -f"
echo ""
echo "服务端口："
echo "  lingyue-starter: 18520"
echo "  lingyue-extract: 18521"
echo "  lingyue-ner:     18522"
