#!/bin/bash

# 根据记忆中的NAS部署方案，启动Launch Daemon守护进程

# 检查NAS挂载状态
if [ ! -d "/Users/chufeng/nas/stock" ]; then
    echo "NAS挂载点不存在，正在创建..."
    mkdir -p "/Users/chufeng/nas/stock"
fi

if ! mount | grep -q "/Users/chufeng/nas/stock"; then
    echo "NAS未挂载，正在挂载..."
    osascript -e 'tell application "Finder" to mount volume "smb://cfdaily:Ccf7561523@192.168.2.154/stock"'
    if [ $? -ne 0 ]; then
        echo "NAS挂载失败"
        exit 1
    fi
    echo "NAS挂载成功"
else
    echo "NAS已挂载"
fi

# 检查Launch Daemon配置文件
LAUNCHD_PLIST="/Library/LaunchDaemons/com.user.nasmount.plist"
if [ ! -f "$LAUNCHD_PLIST" ]; then
    echo "Launch Daemon配置文件不存在，正在复制..."
    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守护进程..."
sudo launchctl load -w "$LAUNCHD_PLIST"
if [ $? -ne 0 ]; then
    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未运行"
    exit 1
fi

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

echo "NAS部署完成"