#!/bin/bash

# 启动Launch Daemon守护进程

# 检查当前用户是否为root
if [ "$(id -u)" -ne 0 ]; then
    echo "请使用root权限运行此脚本"
    echo "例如: sudo $0"
    exit 1
fi

# 检查Launch Daemon配置文件是否存在
LAUNCHD_PLIST="/Library/LaunchDaemons/com.user.nasmount.plist"
if [ ! -f "$LAUNCHD_PLIST" ]; then
    echo "未找到Launch Daemon配置文件"
    echo "正在复制配置文件..."
    cp "/Users/chufeng/.openclaw/workspace-jiangwei/com.user.nasmount.plist" "$LAUNCHD_PLIST"
    if [ $? -ne 0 ]; then
        echo "复制配置文件失败"
        exit 1
    fi
    echo "配置文件复制成功"
else
    echo "Launch Daemon配置文件已存在"
fi

# 检查并创建挂载脚本
MOUNT_SCRIPT="/Users/chufeng/.openclaw/workspace-jiangwei/mount_nas.sh"
if [ ! -f "$MOUNT_SCRIPT" ]; then
    echo "未找到挂载脚本"
    cat > "$MOUNT_SCRIPT" << 'EOF'
#!/bin/bash

# NAS挂载脚本
NAS_URL="//cfdaily:Ccf7561523@192.168.2.154/stock"
MOUNT_POINT="/Users/chufeng/nas/stock"

# 创建挂载点（如果不存在）
mkdir -p "$MOUNT_POINT"

# 检查是否已经挂载
if mount | grep -q "$MOUNT_POINT"; then
    echo "NAS已经挂载在 $MOUNT_POINT"
    exit 0
fi

# 等待网络就绪（最多等待30秒）
for i in {1..30}; do
    if ping -c 1 192.168.2.154 &> /dev/null; then
        break
    fi
    sleep 1
done

# 尝试挂载
echo "正在挂载NAS..."
if /sbin/mount_smbfs "$NAS_URL" "$MOUNT_POINT"; then
    echo "NAS挂载成功：$MOUNT_POINT"
else
    echo "NAS挂载失败"
    exit 1
fi
EOF
    chmod +x "$MOUNT_SCRIPT"
    echo "挂载脚本创建成功"
else
    echo "挂载脚本已存在"
fi

# 加载Launch Daemon
echo "正在加载Launch Daemon..."
if launchctl load -w "$LAUNCHD_PLIST"; then
    echo "Launch Daemon加载成功"
else
    echo "Launch Daemon加载失败"
    exit 1
fi

# 检查Launch Daemon是否正在运行
echo "正在检查Launch Daemon状态..."
if launchctl list com.user.nasmount &> /dev/null; then
    echo "Launch Daemon正在运行"
else
    echo "Launch Daemon未运行"
fi

# 检查NAS是否已挂载
echo "正在检查NAS挂载状态..."
if mount | grep -q "/Users/chufeng/nas/stock"; then
    echo "NAS已成功挂载"
else
    echo "NAS未挂载，正在尝试挂载..."
    "$MOUNT_SCRIPT"
fi

echo "Launch Daemon启动完成"