#!/bin/bash
#
# fix_synology_mount.sh - 修复Synology Docker自动挂载冲突问题
# 问题：Synology自动挂载 /usr/share/zoneinfo/Etc/UTC 和 /app/requirements.txt
# 解决：删除镜像中这两个文件，让Synology可以顺利挂载
#

echo "🔧 开始修复Synology Docker自动挂载冲突问题..."
echo ""

# Docker完整路径
DOCKER="/var/packages/Docker/target/usr/bin/docker"

# 检查镜像是否存在
echo "👉 检查镜像 sanguo_vnpy:v2..."
$DOCKER inspect sanguo_vnpy:v2 > /dev/null 2>&1
if [ $? -ne 0 ]; then
    echo "❌ 错误：找不到镜像 sanguo_vnpy:v2"
    exit 1
fi
echo "✅ 找到镜像 sanguo_vnpy:v2"
echo ""

# 我们需要用另一种方式：用docker save导出，修改，再docker load回去
# 但这需要空间，让我们先试试能否用docker export/import

echo "👉 步骤1: 导出镜像为tar..."
$DOCKER save sanguo_vnpy:v2 -o /tmp/sanguo_vnpy_v2.tar
if [ $? -ne 0 ]; then
    echo "❌ 导出镜像失败"
    exit 1
fi
echo "✅ 镜像导出到 /tmp/sanguo_vnpy_v2.tar"
echo ""

echo "👉 步骤2: 创建临时目录解压..."
TMP_DIR=/tmp/sanguo_vnpy_fixed
mkdir -p $TMP_DIR
cd $TMP_DIR
tar xf /tmp/sanguo_vnpy.tar 2>/dev/null || tar xf /tmp/sanguo_vnpy_v2.tar
if [ $? -ne 0 ]; then
    echo "❌ 解压失败"
    exit 1
fi
echo "✅ 解压完成"
echo ""

echo "👉 步骤3: 删除冲突文件..."
# 删除冲突文件
rm -f $TMP_DIR/usr/share/zoneinfo/Etc/UTC
rm -f $TMP_DIR/app/requirements.txt
echo "✅ 已删除冲突文件:"
echo "   - /usr/share/zoneinfo/Etc/UTC"
echo "   - /app/requirements.txt"
echo ""

echo "👉 步骤4: 重新打包导入..."
cd $TMP_DIR
tar cf /tmp/sanguo_vnpy_fixed.tar .
$DOCKER import /tmp/sanguo_vnpy_fixed.tar sanguo_vnpy:v2-fixed
if [ $? -ne 0 ]; then
    echo "❌ 导入失败"
    exit 1
fi
echo "✅ 导入成功，新镜像: sanguo_vnpy:v2-fixed"
echo ""

echo "👉 步骤5: 清理临时文件..."
rm -rf $TMP_DIR
rm -f /tmp/sanguo_vnpy_v2.tar
rm -f /tmp/sanguo_vnpy_fixed.tar
echo "✅ 清理完成"
echo ""

echo "🎉 修复完成！"
echo ""
echo "现在你可以用新镜像 sanguo_vnpy:v2-fixed 创建容器了"
echo "Synology自动挂载不会再冲突，因为文件已经删除，可以顺利挂载了！"
echo ""
echo "创建容器命令示例:"
echo "  $DOCKER run -d \\"
echo "    --name sanguo_vnpy \\"
echo "    --restart always \\"
echo "    -p 2222:22 \\"
echo "    -p 8000:8000 \\"
echo "    -p 8008:8008 \\"
echo "    -p 8080:8080 \\"
echo "    -p 8088:8088 \\"
echo "    -p 8888:8888 \\"
echo "    -v /volume1/homes/cfdaily/sanguo_vnpy_scripts:/app/scripts \\"
echo "    sanguo_vnpy:v2-fixed"
echo ""
