#!/bin/bash
set -e

IMAGE_NAME="chunlinwang/myubuntu"
TAG="latest"
CONTAINER_NAME="myubuntu"
TMP_FILE="myubuntu_flat.tar"
DATE=$(date +%Y%m%d_%H%M)

echo "========== 开始重打包 myubuntu (单层干净版) =========="

# 1. 确保容器存在并启动
if ! docker ps -a | grep -q "$CONTAINER_NAME"; then
    echo "❌ 容器 $CONTAINER_NAME 不存在！"
    exit 1
fi

echo "[+] 启动容器..."
docker start "$CONTAINER_NAME"

echo "[+] 等待容器就绪..."
sleep 3

# 2. 在容器内执行深度清理
echo "[+] 开始在容器内执行清理..."
docker exec "$CONTAINER_NAME" bash -c '
    echo "→ 清理宝塔日志和备份..."
    rm -rf /www/wwwlogs/*
    echo "日志已清理" > /www/wwwlogs/cleaned.log
    rm -rf /www/backup/*

    echo "→ 清理面板缓存..."
    rm -rf /www/server/panel/logs/*
    rm -rf /www/server/panel/data/tmp/*

    echo "→ 清理 MySQL binlog..."
    rm -f /www/server/data/mysql-bin.* /www/server/data/relay-log.* 2>/dev/null

    echo "→ 清理 PHP sessions 和临时文件..."
    rm -rf /www/server/php/*/var/sessions/* 2>/dev/null
    rm -rf /tmp/* /var/log/* /var/tmp/* /root/.cache/* 2>/dev/null

    echo "→ 清理 apt 缓存..."
    apt-get clean >/dev/null 2>&1
    rm -rf /var/lib/apt/lists/*

    echo "→ 清理其他大日志..."
    find /www -name "*.log" -type f -size +5M -delete 2>/dev/null

    echo "清理完成，当前占用情况："
    df -h
    du -sh /www/* 2>/dev/null | sort -hr
'

# 3. 停止容器准备导出
echo "[+] 停止容器..."
docker stop "$CONTAINER_NAME"

# 4. 备份旧镜像
echo "[+] 备份旧 latest 为 ${DATE}-old..."
if docker image inspect "${IMAGE_NAME}:${TAG}" >/dev/null 2>&1; then
    docker tag "${IMAGE_NAME}:${TAG}" "${IMAGE_NAME}:${DATE}-old"
    echo "旧镜像已备份为 ${IMAGE_NAME}:${DATE}-old"
fi

# 5. 导出 + 导入为单层新镜像
echo "[+] 导出容器为单层 tar..."
docker export "$CONTAINER_NAME" -o "$TMP_FILE"

echo "[+] 导入为新单层 latest 镜像..."
docker import \
  -c 'ENTRYPOINT ["/entrypoint.sh"]' \
  -c 'CMD []' \
  "$TMP_FILE" "${IMAGE_NAME}:${TAG}"

# 6. 清理临时文件
rm -f "$TMP_FILE"

# 7. 完成信息
echo "========== 重打包完成！=========="
echo "新镜像："
docker images "${IMAGE_NAME}" --format "table {{.Repository}}:{{.Tag}}\t{{.Size}}\t{{.ID}}"

echo "当前磁盘占用："
df -h

echo "提示：旧镜像已备份为 ${IMAGE_NAME}:${DATE}-old，可随时回滚。"
