#!/bin/bash
# UAV Speaker Server - 安装脚本
# 解压 tar.gz 后，在此目录运行: sudo ./install.sh
# 程序将被安装到 /opt/uav-speaker/

set -e

HERE="$(cd "$(dirname "$0")" && pwd)"
INSTALL_DIR="/opt/uav-speaker"
SERVICE_NAME="uav-speaker"
SERVICE_FILE="/etc/systemd/system/${SERVICE_NAME}.service"
ENV_FILE="/etc/default/${SERVICE_NAME}"
USER_NAME="${SUDO_USER:-$USER}"

die() { echo "[ERROR] $1"; exit 1; }
ok()  { echo "[OK] $1"; }
info() { echo "[INFO] $1"; }

# ---------- 检查 root ----------
[ "$EUID" -eq 0 ] || die "请使用 sudo 运行: sudo ./install.sh"

# ---------- 检查系统依赖 ----------
info "检查系统依赖..."
command -v python3 >/dev/null || die "缺少 python3，请先安装"
command -v pip3    >/dev/null || die "缺少 pip3，请先安装"
command -v ffmpeg  >/dev/null || die "缺少 ffmpeg，请先安装: sudo apt install ffmpeg"
command -v systemctl >/dev/null || die "缺少 systemd"
ok "系统依赖检查通过"

# ---------- 安装文件到固定目录 ----------
info "安装程序到 $INSTALL_DIR ..."
mkdir -p "$INSTALL_DIR"
cp "$HERE/server.py"        "$INSTALL_DIR/"
cp "$HERE/requirements.txt" "$INSTALL_DIR/"
cp "$HERE/play_test.py"     "$INSTALL_DIR/"
cp -r "$HERE/test_audio"    "$INSTALL_DIR/"

if [ -d "$HERE/packages" ] && [ -n "$(ls -A "$HERE/packages" 2>/dev/null)" ]; then
    cp -r "$HERE/packages" "$INSTALL_DIR/"
fi
ok "程序文件已安装"

# ---------- 安装 Python 依赖 ----------
if [ -d "$INSTALL_DIR/packages" ] && [ -n "$(ls -A "$INSTALL_DIR/packages" 2>/dev/null)" ]; then
    info "检测到离线包，使用本地安装..."
    pip3 install --no-index --find-links "$INSTALL_DIR/packages" --requirement "$INSTALL_DIR/requirements.txt"
    ok "离线依赖安装完成"
else
    info "在线安装 Python 依赖..."
    pip3 install -q --requirement "$INSTALL_DIR/requirements.txt"
    ok "在线依赖安装完成"
fi

# ---------- 环境变量配置 ----------
if [ ! -f "$ENV_FILE" ]; then
    cat > "$ENV_FILE" <<EOF
# UAV Speaker 环境变量配置
# 示例：修改最大录音时长（秒）
# UAVSPK_MAX_AUDIO_SECONDS=30
EOF
    ok "环境变量文件已创建: $ENV_FILE"
fi

# ---------- 安装 systemd 服务 ----------
cat > "$SERVICE_FILE" <<EOF
[Unit]
Description=UAV Speaker Server
After=network.target

[Service]
Type=simple
User=${USER_NAME}
WorkingDirectory=${INSTALL_DIR}
Environment="PYTHONUNBUFFERED=1"
EnvironmentFile=-${ENV_FILE}
ExecStart=/usr/bin/python3 ${INSTALL_DIR}/server.py
Restart=always
RestartSec=5
StandardOutput=journal
StandardError=journal

[Install]
WantedBy=multi-user.target
EOF
chmod 644 "$SERVICE_FILE"
ok "systemd 服务已安装"

# ---------- 启动服务 ----------
systemctl daemon-reload
systemctl enable "$SERVICE_NAME"
systemctl restart "$SERVICE_NAME"

sleep 1
if systemctl is-active --quiet "$SERVICE_NAME"; then
    ok "服务启动成功"
else
    die "服务启动失败，查看日志: journalctl -u $SERVICE_NAME -n 20"
fi

# ---------- 结果 ----------
IP=$(hostname -I 2>/dev/null | awk '{print $1}')
echo ""
echo "========================================"
echo "  UAV Speaker Server 安装完成"
echo "========================================"
echo "  服务: $SERVICE_NAME"
echo "  状态: $(systemctl is-active "$SERVICE_NAME")"
echo "  目录: $INSTALL_DIR"
echo "  API:  http://${IP}:5000/version"
echo ""
echo "  管理命令:"
echo "    sudo systemctl status  $SERVICE_NAME"
echo "    sudo systemctl restart $SERVICE_NAME"
echo "    sudo journalctl -u $SERVICE_NAME -f"
echo "========================================"
