#!/bin/bash
# filepath: install.sh

set -e

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

if [ "$EUID" -ne 0 ]; then 
    echo -e "${RED}Please run as root (use sudo)${NC}"
    exit 1
fi

INSTALL_DIR="/opt/voice-agent"
CONFIG_DIR="/etc/voice-agent"
SERVICE_FILE="/etc/systemd/system/chenxing_agent_service.service"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

echo -e "${GREEN}=== Voice Agent Installation ===${NC}"

sudo cp $SCRIPT_DIR/udev/99-wheeltec_mic.rules /etc/udev/rules.d/
if [ -f /etc/udev/rules.d/chenxing_agent.rules ]; then
    rm /etc/udev/rules.d/chenxing_agent.rules
fi

sudo udevadm control --reload-rules
sudo udevadm trigger

# 检查基本系统依赖
echo -e "${BLUE}Checking system dependencies...${NC}"
MISSING_DEPS=()

if ! ldconfig -p | grep -q "libasound.so"; then
    MISSING_DEPS+=("libasound2")
fi

if ! ldconfig -p | grep -q "libz.so"; then
    MISSING_DEPS+=("zlib1g")
fi

if [ ${#MISSING_DEPS[@]} -gt 0 ]; then
    echo -e "${YELLOW}Missing system dependencies:${NC}"
    for dep in "${MISSING_DEPS[@]}"; do
        echo -e "  - $dep"
    done
    
    if command -v apt-get &> /dev/null; then
        echo -e "${BLUE}Installing dependencies...${NC}"
        apt-get update && apt-get install -y "${MISSING_DEPS[@]}" || {
            echo -e "${RED}Failed to install dependencies.${NC}"
            exit 1
        }
    else
        echo -e "${RED}Please install dependencies manually.${NC}"
        exit 1
    fi
fi

# 检查包内容
echo -e "${BLUE}Checking package contents...${NC}"
MISSING_LIBS=()

if [ ! -f "$SCRIPT_DIR/lib/third_party/libhexaware.so" ]; then
    MISSING_LIBS+=("libhexaware.so")
fi

if [ ${#MISSING_LIBS[@]} -gt 0 ]; then
    echo -e "${YELLOW}⚠ Missing libraries in package:${NC}"
    for lib in "${MISSING_LIBS[@]}"; do
        echo -e "  - $lib"
    done
    echo -e "${YELLOW}Package may be incomplete, but continuing installation...${NC}"
fi

# 停止旧服务
if systemctl is-active --quiet chenxing_agent_service 2>/dev/null; then
    echo "Stopping existing service..."
    systemctl stop chenxing_agent_service
fi

echo "Creating directories..."
mkdir -p "$INSTALL_DIR"/{bin,lib,logs}
mkdir -p "$CONFIG_DIR"

echo "Installing binaries..."
cp -r "$SCRIPT_DIR/bin"/* "$INSTALL_DIR/bin/"
cp "$SCRIPT_DIR/set_default_audio.sh" "$INSTALL_DIR/bin/"
chmod +x "$INSTALL_DIR/bin"/*

echo "Installing libraries..."
cp -r "$SCRIPT_DIR/lib"/* "$INSTALL_DIR/lib/"

echo "Installing resources..."
if [ -d "$SCRIPT_DIR/res" ]; then
    echo "  - Installing res/audio/*.wav files"
    cp -r "$SCRIPT_DIR/res" "$INSTALL_DIR/"
    AUDIO_COUNT=$(find "$INSTALL_DIR/res" -name '*.wav' -o -name '*.WAV' 2>/dev/null | wc -l)
    echo -e "${GREEN}    ✓ $AUDIO_COUNT audio files installed${NC}"
else
    echo -e "${YELLOW}  - Warning: res directory not found in package${NC}"
fi

echo "Installing configuration..."
if [ ! -f "$CONFIG_DIR/config.yaml" ]; then
    cp "$SCRIPT_DIR/config/default_config.yaml" "$CONFIG_DIR/config.yaml"
    echo -e "${YELLOW}Created default config: $CONFIG_DIR/config.yaml${NC}"
else
    echo -e "${YELLOW}Config exists, saved new version as config.yaml.new${NC}"
    cp "$SCRIPT_DIR/config/default_config.yaml" "$CONFIG_DIR/config.yaml.new"
fi

# 复制配置文件到程序期望的位置（使用实际文件而不是符号链接）
mkdir -p "$INSTALL_DIR/config"
# 强制删除可能存在的符号链接
rm -f "$INSTALL_DIR/config/config.yaml"
rm -f "$INSTALL_DIR/config/default_config.yaml"
# 复制实际文件
cp "$CONFIG_DIR/config.yaml" "$INSTALL_DIR/config/config.yaml"
cp "$CONFIG_DIR/config.yaml" "$INSTALL_DIR/config/default_config.yaml"

# 程序使用相对路径 ../config/，创建 /opt/config 的符号链接
mkdir -p /opt/config
ln -sf "$INSTALL_DIR/config/default_config.yaml" /opt/config/default_config.yaml
ln -sf "$INSTALL_DIR/config/config.yaml" /opt/config/config.yaml

# 复制.env文件（优先使用打包时包含的.env）
if [ ! -f "$CONFIG_DIR/.env" ]; then
    if [ -f "$SCRIPT_DIR/config/.env" ]; then
        # 打包时包含了实际的.env文件
        cp "$SCRIPT_DIR/config/.env" "$CONFIG_DIR/.env"
        echo -e "${GREEN}Copied .env file: $CONFIG_DIR/.env${NC}"
        echo -e "${YELLOW}⚠️  Please verify $CONFIG_DIR/.env settings!${NC}"
        echo ""
    elif [ -f "$SCRIPT_DIR/config/.env.example" ]; then
        # 只有.env.example模板
        cp "$SCRIPT_DIR/config/.env.example" "$CONFIG_DIR/.env"
        echo -e "${YELLOW}Created .env template: $CONFIG_DIR/.env${NC}"
        echo -e "${YELLOW}⚠️  Please edit $CONFIG_DIR/.env with your credentials!${NC}"
        echo ""
    else
        echo -e "${RED}Warning: No .env file found in package!${NC}"
        echo -e "${YELLOW}Please manually create $CONFIG_DIR/.env${NC}"
    fi
else
    echo -e "${YELLOW}.env file exists, skipping${NC}"
fi

# 创建符号链接确保程序能找到配置和资源
echo "Creating symbolic links..."
ln -sf "$CONFIG_DIR/.env" "$INSTALL_DIR/.env"
ln -sf "$CONFIG_DIR/.env" /opt/.env
echo -e "${GREEN}  ✓ .env symlinks created${NC}"

# 创建 res 目录的符号链接（确保相对路径 ../res 可用）
if [ -d "$INSTALL_DIR/res" ]; then
    rm -f /opt/res
    ln -sf "$INSTALL_DIR/res" /opt/res
    echo -e "${GREEN}  ✓ Resources symlink: /opt/res -> $INSTALL_DIR/res${NC}"
fi

# 创建模型目录并下载模型文件
echo "Setting up models directory..."
mkdir -p /opt/res/models

# 检查模型是否已存在，避免重复下载
MATCHA_DIR_EXISTS=false
SHERPA_DIR_EXISTS=false

# 检查 matcha 模型目录是否存在
if [ -d "/opt/res/models/matcha-icefall-zh-en" ] || [ -d "/opt/res/models/matcha" ]; then
    echo -e "${GREEN}  ✓ Matcha model already exists, skipping download${NC}"
    MATCHA_DIR_EXISTS=true
fi

# 检查 sherpa 模型目录是否存在
if [ -d "/opt/res/models/sherpa-onnx-streaming-zipformer-zh-int8-2025-06-30" ] || [ -d "/opt/res/models/sherpa" ]; then
    echo -e "${GREEN}  ✓ Sherpa model already exists, skipping download${NC}"
    SHERPA_DIR_EXISTS=true
fi

# 创建临时目录用于下载模型文件
tmp_dir="$SCRIPT_DIR/tmp"
mkdir -p "$tmp_dir"
echo -e "${GREEN}  ✓ Created temporary directory: $tmp_dir${NC}"

# 检查并安装 unzip 工具（如果需要）
if ! command -v unzip &> /dev/null; then
    echo -e "${BLUE}Installing unzip utility...${NC}"
    if command -v apt-get &> /dev/null; then
        apt-get update && apt-get install -y unzip || {
            echo -e "${RED}Failed to install unzip.${NC}"
            exit 1
        }
    else
        echo -e "${RED}Please install unzip manually.${NC}"
        exit 1
    fi
fi

# 定义模型文件URL
MATCHA_MODEL_URL="http://im.daystar.cloud:1088/daystarBot/RELEASE/SYSB/models/matcha-icefall-zh-en.zip"
SHERPA_MODEL_URL="http://im.daystar.cloud:1088/daystarBot/RELEASE/SYSB/models/sherpa-onnx-streaming-zipformer-zh-int8-2025-06-30.zip"

# 下载并解压第一个模型 (matcha-icefall-zh-en)，仅当不存在时
if [ "$MATCHA_DIR_EXISTS" = false ]; then
    echo "Downloading matcha-icefall-zh-en model..."
    if wget -O "$tmp_dir/matcha-icefall-zh-en.zip" "$MATCHA_MODEL_URL"; then
        echo "Extracting matcha-icefall-zh-en model to /opt/res/models/ ..."
        unzip -q "$tmp_dir/matcha-icefall-zh-en.zip" -d /opt/res/models/ || {
            echo -e "${RED}  ✗ Failed to extract matcha model${NC}"
        }
        echo -e "${GREEN}  ✓ Matcha model extracted successfully${NC}"
    else
        echo -e "${YELLOW}  ⚠ Failed to download matcha model.${NC}"
    fi
fi

# 下载并解压第二个模型 (sherpa-onnx-streaming-zipformer-zh-int8-2025-06-30)，仅当不存在时
if [ "$SHERPA_DIR_EXISTS" = false ]; then
    echo "Downloading sherpa-onnx-streaming-zipformer-zh-int8-2025-06-30 model..."
    if wget -O "$tmp_dir/sherpa-onnx-streaming-zipformer-zh-int8-2025-06-30.zip" "$SHERPA_MODEL_URL"; then
        echo "Extracting sherpa-onnx-streaming-zipformer-zh-int8-2025-06-30 model to /opt/res/models/ ..."
        unzip -q "$tmp_dir/sherpa-onnx-streaming-zipformer-zh-int8-2025-06-30.zip" -d /opt/res/models/ || {
            echo -e "${RED}  ✗ Failed to extract sherpa model${NC}"
        }
        echo -e "${GREEN}  ✓ Sherpa model extracted successfully${NC}"
    else
        echo -e "${YELLOW}  ⚠ Failed to download sherpa model.${NC}"
    fi
fi

# 清理临时文件
rm -rf "$tmp_dir"
echo -e "${GREEN}  ✓ Models setup completed${NC}"

# 创建 logs 符号链接到统一日志目录
mkdir -p /var/log/voice-agent
chmod 755 /var/log/voice-agent

# 删除旧的logs目录或符号链接
if [ -L "$INSTALL_DIR/logs" ]; then
    # 如果是符号链接，直接删除
    rm -f "$INSTALL_DIR/logs"
    echo -e "${YELLOW}  Removed old logs symlink${NC}"
elif [ -d "$INSTALL_DIR/logs" ]; then
    # 如果是目录，移动现有日志到新位置，然后删除目录
    echo -e "${YELLOW}  Moving existing logs to /var/log/voice-agent/${NC}"
    if [ "$(ls -A "$INSTALL_DIR/logs" 2>/dev/null)" ]; then
        cp -r "$INSTALL_DIR/logs"/* /var/log/voice-agent/ 2>/dev/null || true
    fi
    rm -rf "$INSTALL_DIR/logs"
    echo -e "${YELLOW}  Removed old logs directory${NC}"
fi

ln -sf /var/log/voice-agent "$INSTALL_DIR/logs"
echo -e "${GREEN}  ✓ Logs symlink: $INSTALL_DIR/logs -> /var/log/voice-agent${NC}"

# 验证安装后的依赖（使用正确的 LD_LIBRARY_PATH）
echo ""
echo -e "${BLUE}Verifying installation...${NC}"
echo "Installed third-party libraries:"
if [ -d "$INSTALL_DIR/lib/third_party" ]; then
    ls -lh "$INSTALL_DIR/lib/third_party/" 2>/dev/null || echo "  (none)"
else
    echo "  (none)"
fi

echo ""
echo -e "${BLUE}Checking binary dependencies...${NC}"
export LD_LIBRARY_PATH="$INSTALL_DIR/lib:$INSTALL_DIR/lib/third_party:$LD_LIBRARY_PATH"
UNRESOLVED=$(ldd "$INSTALL_DIR/bin/voice_agent" 2>&1 | grep "not found" || true)

if [ -n "$UNRESOLVED" ]; then
    echo -e "${YELLOW}⚠ Some dependencies not resolved:${NC}"
    echo "$UNRESOLVED"
    echo ""
    echo -e "${YELLOW}This may be normal if optional features are disabled.${NC}"
    echo -e "${YELLOW}The service will attempt to start anyway.${NC}"
else
    echo -e "${GREEN}✓ All dependencies resolved${NC}"
fi

echo ""
echo "Creating systemd service..."

# 检测目标主机上的 OpenSSL 库路径
OPENSSL_LIB_PATHS=""
for user_home in /home/*; do
    OPENSSL_DIR="$user_home/openssl-OpenSSL_1_1_1w/install/lib"
    if [ -d "$OPENSSL_DIR" ] && [ -f "$OPENSSL_DIR/libssl.so.1.1" ]; then
        echo -e "${GREEN}Found OpenSSL at: $OPENSSL_DIR${NC}"
        OPENSSL_LIB_PATHS=":$OPENSSL_DIR"
        break
    fi
done

# 如果没有找到用户目录的 OpenSSL，检查 root 用户
if [ -z "$OPENSSL_LIB_PATHS" ]; then
    OPENSSL_DIR="/root/openssl-OpenSSL_1_1_1w/install/lib"
    if [ -d "$OPENSSL_DIR" ] && [ -f "$OPENSSL_DIR/libssl.so.1.1" ]; then
        echo -e "${GREEN}Found OpenSSL at: $OPENSSL_DIR${NC}"
        OPENSSL_LIB_PATHS=":$OPENSSL_DIR"
    fi
fi

# 构建完整的 LD_LIBRARY_PATH
LD_LIB_PATH="/opt/voice-agent/lib:/opt/voice-agent/lib/third_party${OPENSSL_LIB_PATHS}"

cat > "$SERVICE_FILE" << SERVICEEOF
[Unit]
Description=Voice Agent Service
After=network.target sound.target

[Service]
Type=simple
User=root
WorkingDirectory=/opt/voice-agent
# 加载环境变量文件
EnvironmentFile=-/etc/voice-agent/.env
Environment="LD_LIBRARY_PATH=${LD_LIB_PATH}"
# 使用位置参数传递配置文件路径
ExecStart=/opt/voice-agent/bin/voice_agent config/default_config.yaml
Restart=always
RestartSec=5
StandardOutput=journal
StandardError=journal

LimitNOFILE=65536
LimitNPROC=4096

[Install]
WantedBy=multi-user.target
SERVICEEOF

echo -e "${GREEN}  ✓ Service file created: $SERVICE_FILE${NC}"

echo "Reloading systemd daemon..."
systemctl daemon-reload

echo "Enabling service..."
systemctl enable chenxing_agent_service

echo "Starting service..."
systemctl start chenxing_agent_service

sleep 2
if systemctl is-active --quiet chenxing_agent_service; then
    echo ""
    echo -e "${GREEN}✅ Installation completed successfully!${NC}"
    echo ""
    echo -e "${BLUE}=== Installation Summary ===${NC}"
    echo -e "Installation directory: ${GREEN}/opt/voice-agent${NC}"
    echo -e "Configuration directory: ${GREEN}/etc/voice-agent${NC}"
    echo -e "Logs directory: ${GREEN}/var/log/voice-agent${NC}"
    echo -e "Resources directory: ${GREEN}/opt/voice-agent/res${NC}"
    echo -e "Audio files: ${GREEN}/opt/voice-agent/res/audio/*.wav${NC}"
    echo ""
    systemctl status chenxing_agent_service --no-pager -l
    echo ""
    echo "Useful commands:"
    echo "  systemctl restart chenxing_agent_service     # Restart service"
    echo "  journalctl -u chenxing_agent_service -f      # View real-time logs"
    echo "  tail -f /var/log/voice-agent/*.log  # View application logs"
    echo "  ls -lh /opt/voice-agent/res/audio/  # Check audio resources"
    echo ""
    echo -e "${YELLOW}⚠️  Configuration files:${NC}"
    echo "    /etc/voice-agent/.env         - Edit credentials here"
    echo "    /etc/voice-agent/config.yaml  - Edit settings here"
else
    echo ""
    echo -e "${RED}❌ Service failed to start.${NC}"
    echo "Check logs:"
    echo "  journalctl -u chenxing_agent_service -n 50"
    echo ""
    echo "Debug commands:"
    echo "  export LD_LIBRARY_PATH=/opt/voice-agent/lib:/opt/voice-agent/lib/third_party"
    echo "  ldd /opt/voice-agent/bin/voice_agent"
    echo "  cd /opt/voice-agent && ./bin/voice_agent config/default_config.yaml"
    exit 1
fi
