#!/bin/sh
# 用法：./diff_zip_sh.sh zip1.zip zip2.zip diff.zip

usage() {
    echo "用法: $0 <old.zip> <new.zip> <diff.zip>"
    exit 1
}

[ "$#" -eq 3 ] || usage

zip1=$1
zip2=$2
diffzip=$3

# 检查文件
for f in "$zip1" "$zip2"; do
    [ -f "$f" ] || { echo "文件不存在: $f"; exit 1; }
done

# 临时目录
tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT

tmp1=$tmp/1
tmp2=$tmp/2
tmp3=$tmp/3

mkdir -p "$tmp1" "$tmp2" "$tmp3"

# 解压
unzip -q "$zip1" -d "$tmp1"
unzip -q "$zip2" -d "$tmp2"

# 递归对比
find "$tmp2" -type f | while IFS= read -r f2; do
    rel=${f2#$tmp2/}
    f1=$tmp1/$rel
    if [ -f "$f1" ] && cmp -s "$f1" "$f2"; then
        continue   # 内容相同，跳过
    fi
    dest=$tmp3/$rel
    mkdir -p "$(dirname "$dest")"
    cp "$f2" "$dest"
done

# 无差异
[ -z "$(find "$tmp3" -type f 2>/dev/null)" ] && {
    echo "两个 ZIP 内容完全一致，无需输出。"
    exit 0
}

# 打包
(cd "$tmp3" && zip -qr ../out.zip .)
mv "$tmp/out.zip" "$diffzip"
echo "✅ 差异文件已保存到 $diffzip"
