#!/bin/bash
BASE_DIR="/var/www/cydia"
DOMAIN="http://apt.354771.xyz"
cd $BASE_DIR

echo "📦 正在执行 v45.0 稳定版详情页重构..."

# 1. 生成原始账本
dpkg-scanpackages -m debs /dev/null > Packages.raw

# 2. 使用 Python 进行 URL 安全编码
python3 -c '
import sys, base64, json, re, urllib.parse

content = open("Packages.raw").read()
blocks = content.strip().split("\n\n")
new_blocks = []

for block in blocks:
    name = re.search(r"^Name:\s*(.*)", block, re.M)
    ver = re.search(r"^Version:\s*(.*)", block, re.M)
    desc = re.search(r"^Description:\s*(.*)", block, re.M)
    
    n = name.group(1) if name else "Unknown"
    v = ver.group(1) if ver else "0.0.1"
    # 截断简介，防止 URL 过长导致加载失败
    d = desc.group(1) if desc else "暂无介绍"
    if len(d) > 100: d = d[:100] + "..." 
    
    info_json = json.dumps({"n": n, "v": v, "d": d}, ensure_ascii=False)
    b64_info = base64.b64encode(info_json.encode("utf-8")).decode("utf-8")
    # 关键点：进行 URL 编码
    safe_info = urllib.parse.quote(b64_info)
    
    block = re.sub(r"\n(Sileo)?Depiction:[^\n]*", "", block)
    new_dep = f"\nDepiction: {sys.argv[1]}/depictions/index.html?info={safe_info}"
    new_blocks.append(block + new_dep)

print("\n\n".join(new_blocks))
' "$DOMAIN" > Packages

# 3. 扫尾
bzip2 -fk Packages
gzip -fk Packages > Packages.gz
rm Packages.raw

echo "✅ 修复完成！"
