#!/usr/bin/env python3
# gnucego-packages-gen.py — gera o catálogo de pacotes + tracker + security-tracker
# do GNUcego em gnucego.org/pacotes/ (estático).
#
# Copyright (C) 2026 GNUcego contributors — GPLv3+
#
# Estrutura gerada em /media/wellton/backup/gnucego-site/pacotes/:
#   index.html                      -> catálogo com busca (todos os pacotes)
#   pkg/<nome>.html                 -> página por pacote (versões Exu/Ogum/Segurança)
#   security/index.html             -> security-tracker (CVEs cruzadas com os pacotes GNUcego)
#   security/pkg/<nome>.html        -> CVEs de um pacote específico
#   packages.css                    -> folha de estilo (tema GNUcego dark)
#
# Fontes:
#   - índices Packages do espelho (exu/ogum/exu-security)
#   - security-tracker do Debian (git) para as CVEs
#
# Uso: python3 gnucego-packages-gen.py [--only-security]

import os
import re
import sys
import gzip
import json
from collections import defaultdict

MIRROR = "/media/wellton/backup/debian"
SITE = "/media/wellton/backup/gnucego-site"
SECTRACK = "/media/wellton/backup/debian/gnucego/security-tracker"

BASE = "/pacotes"

DISTS = [
    ("exu", "Exu", "stable", "Estável"),
    ("exu-security", "Exu (segurança)", "stable-security", "Atualizações de segurança"),
    ("ogum", "Ogum", "testing", "Teste"),
]

ARCHES = ("binary-amd64", "binary-all")

# pacotes compilados/reempacotados por NÓS (destacados no catálogo)
GNUC_PACKAGES = {
    "emacs", "gnucego-keyring", "gnucego-theme", "icecat",
    "linux-libre", "linux-libre-headers", "linux-libre-lts",
    "linux-libre-lts-headers", "ungoogled-chromium",
}

# mapeamento: pacote GNUcego -> pacote Debian correspondente (para cruzar CVEs)
# quando a gente recompila um pacote do Debian com outro nome/número.
GNUC_TO_DEBIAN = {
    "icecat": "iceweasel",          # IceCat substitui o firefox/iceweasel (que não existe mais)
    "ungoogled-chromium": "chromium",
}

# Cruzamento GNUcego (opção 1): mapa manual de CVEs que a GNUcego JÁ corrigiu,
# com a versão GNUcego em que cada correção entrou.
# Formato: { "pacote": { "CVE-XXXX-YYYY": "1:30.1-1+gnucego2" } }
# Isto sobrepõe o status "do Debian" com o status real da GNUcego.
GNUC_FIXED_CVES = {
    "emacs": {
        "CVE-2026-96269": "1:30.1-1+gnucego2",
        "CVE-2026-6861": "1:30.1-1+gnucego2",
    },
}


def esc(s):
    return (s or "").replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")


def parse_packages(path):
    if path.endswith(".gz"):
        with gzip.open(path, "rt", encoding="utf-8", errors="replace") as f:
            text = f.read()
    else:
        with open(path, encoding="utf-8", errors="replace") as f:
            text = f.read()
    blocks = []
    for raw in text.split("\n\n"):
        raw = raw.strip()
        if not raw:
            continue
        rec = {}
        key = None
        for line in raw.splitlines():
            if line.startswith(" ") and key:
                rec[key] = rec.get(key, "") + "\n" + line.strip()
                continue
            if ":" in line:
                k, _, v = line.partition(":")
                key = k.strip()
                rec[key] = v.strip()
        if "Package" in rec and "Version" in rec:
            blocks.append(rec)
    return blocks


def build_pkg_index():
    idx = defaultdict(lambda: defaultdict(list))
    names = set()
    for dist, label, serie, descr in DISTS:
        for arch in ARCHES:
            p = os.path.join(MIRROR, "dists", dist, "main", arch, "Packages")
            if not os.path.isfile(p):
                continue
            for rec in parse_packages(p):
                idx[rec["Package"]][dist].append(rec)
                names.add(rec["Package"])
    return idx, sorted(names)


# ---------------------------------------------------------------------------
# CSS
# ---------------------------------------------------------------------------
CSS = '''*{margin:0;padding:0;box-sizing:border-box}
body{background:#0a0a0a;color:#d4d4d4;font-family:monospace;line-height:1.6}
a{color:#ff4d5e;text-decoration:none}
a:hover{text-decoration:underline}
code{background:#131313;padding:2px 6px;border-radius:3px;color:#ff8080}
.topbar{display:flex;align-items:center;justify-content:space-between;gap:16px;padding:14px 20px;background:#131313;border-bottom:1px solid #2a2a2a;flex-wrap:wrap}
.topbar .brand{color:#fff;font-weight:bold;font-size:16px;text-decoration:none}
.topbar form{display:flex;gap:8px}
.topbar input{background:#0a0a0a;border:1px solid #2a2a2a;color:#d4d4d4;padding:8px 12px;border-radius:5px;font-family:monospace;min-width:260px}
.topbar button{background:#e42132;color:#fff;border:none;padding:8px 16px;border-radius:5px;cursor:pointer;font-weight:bold}
.topbar button:hover{background:#c1121f}
.wrap{max-width:1000px;margin:0 auto;padding:24px 20px}
h1{color:#e42132;font-size:22px;margin-bottom:6px}
h2{color:#ff4d5e;font-size:16px;margin:26px 0 12px;padding-bottom:6px;border-bottom:1px solid #2a2a2a}
.lead{color:#8b949e;font-size:13px;margin-bottom:18px}
.count{color:#8b949e;font-size:12px;margin-bottom:12px}
.breadcrumb{color:#8b949e;font-size:12px;margin-bottom:12px}
.badges{margin:10px 0}
.badge-gnuc{display:inline-block;background:#7f1d1d;color:#ffb3b8;font-size:11px;padding:3px 8px;border-radius:4px;margin-left:6px;font-weight:bold}
.badge{display:inline-block;font-size:11px;padding:3px 8px;border-radius:4px;margin:2px 4px 2px 0}
.badge-fixed{background:#0f3d1f;color:#7ef0a5}
.badge-vuln{background:#3d0f0f;color:#ff9e9e}
.badge-unfixed{background:#3d2a0f;color:#ffd28a}
.pkgcard{display:block;background:#131313;border:1px solid #2a2a2a;border-radius:6px;padding:10px 14px;margin:6px 0;color:#d4d4d4;text-decoration:none}
.pkgcard:hover{border-color:#e42132}
.pkgcard code{background:none;color:#fff;padding:0}
.panel{background:#131313;border:1px solid #2a2a2a;border-radius:8px;padding:18px;margin:16px 0}
table{width:100%;border-collapse:collapse;font-size:13px}
td,th{border:1px solid #2a2a2a;padding:8px 10px;text-align:left;vertical-align:top}
th{background:#0d0d0d;color:#ff4d5e}
table.kv th{width:180px}
.back{color:#8b949e;font-size:13px;margin-top:20px}
footer{text-align:center;color:#8b949e;font-size:12px;padding:20px;border-top:1px solid #2a2a2a;margin-top:30px}
.search-hint{color:#8b949e;font-size:12px;margin:8px 0}
.homepage{margin:8px 0 14px;font-size:13px;color:#8b949e}
.homepage a{color:#ff4d5e;word-break:break-all}
'''


def write_css(out_dir):
    with open(os.path.join(out_dir, "packages.css"), "w", encoding="utf-8") as f:
        f.write(CSS)


def render_index(names, json_list, json_gnuc):
    # cards "estáticos" (todos) para o fallback sem JS — a busca filtra client-side via JS
    all_cards = ""
    for name in names:
        is_gnuc = name in GNUC_PACKAGES
        badge = ' <span class="badge-gnuc">GNUcego</span>' if is_gnuc else ""
        all_cards += f'<a class="pkgcard" href="pkg/{esc(name)}.html"><code>{esc(name)}</code>{badge}</a>\n'

    return f'''<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Pacotes — GNUcego</title>
<link rel="stylesheet" href="packages.css">
</head>
<body>
<header class="topbar">
  <a class="brand" href="index.html">&#128230; Pacotes GNUcego</a>
  <input type="text" id="search" placeholder="Buscar pacote (ex.: emacs, icecat, linux-libre…)" autocomplete="off">
</header>
<main class="wrap">
<h1>Catálogo de pacotes</h1>
<p class="lead">Todos os pacotes dos repositórios <strong>Exu</strong> (estável) e <strong>Ogum</strong> (teste). Os marcados como <span class="badge-gnuc">GNUcego</span> são compilados ou reempacotados pela própria distribuição. Veja também o <a href="security/index.html">rastreamento de segurança (CVEs)</a>.</p>
<p class="count" id="count">{len(names)} pacotes (total)</p>
<div id="results">
{all_cards}
</div>
<p class="back"><a href="https://gnucego.org/">&#8592; Voltar à página inicial</a></p>
</main>
<footer>GNUcego &mdash; distribuição GNU/Linux-libre 100% livre (FSDG) &middot; <a href="https://gnucego.org/">gnucego.org</a></footer>
<script>
(function(){{
  var input = document.getElementById('search');
  var results = document.getElementById('results');
  var count = document.getElementById('count');
  // índice dos pacotes, embutido (busca client-side, sem backend)
  var pkgs = {json_list};
  var gnucPkgs = {json_gnuc};

  function render(list){{
    if(list.length > 5000){{ 
      results.innerHTML = '<p class="search-hint">'+list.length+' resultados. Refine a busca para ver a lista.</p>';
      count.textContent = list.length + ' pacote(s)';
      return;
    }}
    var html = '';
    for(var i=0;i<list.length;i++){{
      var n = list[i];
      var badge = (gnucPkgs.indexOf(n) >= 0) ? ' <span class="badge-gnuc">GNUcego</span>' : '';
      html += '<a class="pkgcard" href="pkg/'+n+'.html"><code>'+n+'</code>'+badge+'</a>';
    }}
    results.innerHTML = html;
    count.textContent = list.length + ' pacote(s)';
  }}

  input.addEventListener('input', function(){{
    var q = input.value.trim().toLowerCase();
    if(!q){{ render(pkgs); return; }}
    var out = [];
    for(var i=0;i<pkgs.length;i++){{
      if(pkgs[i].toLowerCase().indexOf(q) !== -1) out.push(pkgs[i]);
    }}
    render(out);
  }});
  // lê ?q= da URL (se alguém chegar com query)
  var m = location.search.match(/[?&]q=([^&]+)/);
  if(m){{ input.value = decodeURIComponent(m[1]); input.dispatchEvent(new Event('input')); }}
}})();
</script>
</body>
</html>
'''


def render_pkg_page(name, idx):
    recs_by_dist = idx.get(name)
    if not recs_by_dist:
        return None
    is_gnuc = name in GNUC_PACKAGES

    canon = None
    for d, *_ in DISTS:
        if d in recs_by_dist:
            canon = recs_by_dist[d][0]
            break
    descr = canon.get("Description", "")
    dlines = descr.split("\n")
    short = dlines[0] if dlines else ""
    longd = "\n".join(dlines[1:]).strip() if len(dlines) > 1 else ""

    badges = f'<span class="badge-gnuc">compilado no GNUcego</span>' if is_gnuc else ""

    # Link do site upstream (campo Homepage), quando existir
    homepage = canon.get("Homepage", "")
    homepage_html = ""
    if homepage:
        homepage_html = (f'<p class="homepage">&#127760; Site do projeto: '
                         f'<a href="{esc(homepage)}" rel="noopener">{esc(homepage)}</a></p>')

    rows = ""
    for dist, label, serie, descr_ in DISTS:
        if dist not in recs_by_dist:
            continue
        for rec in recs_by_dist[dist]:
            arch = rec.get("Architecture", "")
            fn = rec.get("Filename", "")
            size = int(rec.get("Size", 0))
            size_h = f"{size/1024/1024:.1f} MB" if size else "&mdash;"
            link = f'<a href="https://repo.gnucego.org/{fn}">.deb</a>' if fn else "&mdash;"
            rows += (f'<tr><td><code>{esc(label)}</code></td>'
                     f'<td><code>{esc(rec.get("Version",""))}</code></td>'
                     f'<td>{arch}</td><td>{size_h}</td><td>{link}</td></tr>\n')

    meta = [
        ("Seção", canon.get("Section", "&mdash;")),
        ("Prioridade", canon.get("Priority", "&mdash;")),
        ("Mantenedor", canon.get("Maintainer", "&mdash;")),
        ("Site do projeto (upstream)", '<a href="' + esc(homepage) + '" rel="noopener">' + esc(homepage) + '</a>' if homepage else "&mdash;"),
        ("Depende de", canon.get("Depends", "&mdash;")),
        ("Fornece (Provides)", canon.get("Provides", "&mdash;")),
        ("Substitui (Replaces)", canon.get("Replaces", "&mdash;")),
        ("Conflita (Conflicts)", canon.get("Conflicts", "&mdash;")),
    ]
    meta_rows = ""
    for k, v in meta:
        meta_rows += f'<tr><th>{k}</th><td><code>{esc(v)}</code></td></tr>\n'

    sec_link = f'<p><a href="../security/pkg/{name}.html">Ver CVEs deste pacote &#8594;</a></p>'

    return f'''<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{esc(name)} — Pacotes GNUcego</title>
<link rel="stylesheet" href="../packages.css">
</head>
<body>
<header class="topbar">
  <a class="brand" href="../index.html">&#128230; Pacotes GNUcego</a>
  <form action="../index.html" method="get">
    <input type="text" name="q" placeholder="Buscar pacote…" value="">
    <button type="submit">Buscar</button>
  </form>
</header>
<main class="wrap">
<p class="breadcrumb"><a href="../index.html">Pacotes</a> / <code>{esc(name)}</code></p>
<h1><code>{esc(name)}</code></h1>
<div class="badges">{badges}</div>
<p>{esc(short)}</p>
{homepage_html}

<div class="panel">
<h2>Versões por repositório</h2>
<table>
<thead><tr><th>Repositório</th><th>Versão</th><th>Arquitetura</th><th>Tamanho</th><th>Download</th></tr></thead>
<tbody>{rows}</tbody>
</table>
</div>

<div class="panel">
<h2>Informações do pacote</h2>
<table class="kv">{meta_rows}</table>
</div>

{sec_link}
<p class="back"><a href="../index.html">&#8592; Voltar ao catálogo</a></p>
</main>
<footer>GNUcego &mdash; distribuição GNU/Linux-libre 100% livre (FSDG) &middot; <a href="/">gnucego.org</a></footer>
</body>
</html>
'''


# ---------------------------------------------------------------------------
# Security tracker
# ---------------------------------------------------------------------------

def parse_cve_list():
    """Parseia data/CVE/list do Debian -> {pkg_debian -> [ (cve, descr, status_record) ]}."""
    path = os.path.join(SECTRACK, "data", "CVE", "list")
    if not os.path.isfile(path):
        return {}
    pkg_cves = defaultdict(list)
    cur_cve = None
    cur_descr = ""
    # descrição também está em data/CVE/list mas resumida; usamos o que temos
    with open(path, encoding="utf-8", errors="replace") as f:
        for line in f:
            line = line.rstrip("\n")
            m = re.match(r'^CVE-\d{4}-\d+ (?:\s*\(([^)]*)\))? *(.*)$', line)
            if m and not line.startswith("\t"):
                cur_cve = line.split()[0]
                cur_descr = line[len(cur_cve):].strip()
                # remove "(...)" inicial se presente
                cur_descr = re.sub(r'^\(\s*\)\s*', '', cur_descr)
                continue
            if line.startswith("\t- "):
                # entrada de pacote: "\t- pkg [release] <status> (bug)"
                body = line[3:].strip()
                parts = body.split()
                if not parts:
                    continue
                pkg = parts[0]
                # junta a versão/status: o resto
                rest = " ".join(parts[1:])
                pkg_cves[pkg].append((cur_cve, cur_descr, rest))
    return pkg_cves


def status_badge(status_text):
    s = status_text.lower()
    if "<not-affected>" in s or "not-affected" in s:
        return '<span class="badge badge-fixed">não afetado</span>'
    if "<unfixed>" in s or "unfixed" in s:
        return '<span class="badge badge-unfixed">não corrigido</span>'
    if "<removed>" in s or "removed" in s or "end-of-life" in s:
        return '<span class="badge badge-fixed">removido/último</span>'
    if "<itp>" in s or "itp" in s.lower():
        return '<span class="badge badge-unfixed">ainda não empacotado</span>'
    # tem versão de fix
    if re.search(r'\d', s):
        return '<span class="badge badge-fixed">corrigido</span>'
    return '<span class="badge badge-fixed">registrado</span>'


def debian_pkg_for_gnuc(name):
    """Um pacote GNUcego pode mapear para um nome Debian (para achar CVEs)."""
    if name in GNUC_TO_DEBIAN:
        return GNUC_TO_DEBIAN[name]
    return name


def render_security_index(pkg_cves):
    # só os pacotes GNUcego (os que a gente compila)
    gnuc = sorted(GNUC_PACKAGES)
    rows = ""
    for name in gnuc:
        debname = debian_pkg_for_gnuc(name)
        cves = pkg_cves.get(debname, [])
        n_vuln = sum(1 for _, _, s in cves if "<unfixed>" in s or "unfixed" in s.lower())
        n_total = len(cves)
        badge = ('<span class="badge badge-vuln">%d não corrigidas</span>' % n_vuln) if n_vuln else \
                ('<span class="badge badge-fixed">todas corrigidas</span>' if n_total else '&mdash;')
        mapeado = "" if debname == name else ' <span class="search-hint">(map. Debian: ' + esc(debname) + ')</span>'
        rows += (f'<tr><td><a href="pkg/{name}.html"><code>{esc(name)}</code></a>{mapeado}'
                 f'</td><td>{n_total}</td><td>{badge}</td></tr>\n')

    return f'''<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Rastreamento de segurança (CVEs) — GNUcego</title>
<link rel="stylesheet" href="../packages.css">
</head>
<body>
<header class="topbar">
  <a class="brand" href="../index.html">&#128230; Pacotes GNUcego</a>
  <form action="../index.html" method="get">
    <input type="text" name="q" placeholder="Buscar pacote…" value="">
    <button type="submit">Buscar</button>
  </form>
</header>
<main class="wrap">
<p class="breadcrumb"><a href="../index.html">Pacotes</a> / <code>segurança</code></p>
<h1>Rastreamento de segurança (CVEs)</h1>
<p class="lead">Status das vulnerabilidades (CVEs) nos pacotes que a GNUcego compila ou reempacota. Os dados vêm do <a href="https://security-tracker.debian.org/">security-tracker do Debian</a> (que rastreia as CVEs dos pacotes que espelhamos), cruzados com os nossos pacotes próprios.</p>
<p class="lead">Legenda: <span class="badge badge-vuln">não corrigido</span> <span class="badge badge-fixed">corrigido</span> <span class="badge badge-fixed">não afetado</span></p>
<div class="panel">
<table>
<thead><tr><th>Pacote GNUcego</th><th>CVEs rastreadas</th><th>Status</th></tr></thead>
<tbody>{rows}</tbody>
</table>
</div>
<p class="back"><a href="../index.html">&#8592; Voltar ao catálogo</a></p>
</main>
<footer>GNUcego &mdash; distribuição GNU/Linux-libre 100% livre (FSDG) &middot; <a href="/">gnucego.org</a></footer>
</body>
</html>
'''


def render_security_pkg(name, pkg_cves):
    debname = debian_pkg_for_gnuc(name)
    cves = pkg_cves.get(debname, [])
    cves_sorted = sorted(cves, key=lambda x: x[0], reverse=True)
    gnuc_fixed = GNUC_FIXED_CVES.get(name, {})

    rows = ""
    for cve, descr, status in cves_sorted:
        cve_link = f'<a href="https://security-tracker.debian.org/tracker/{cve}">{esc(cve)}</a>'
        # status GNUcego (opção 1): se a gente já corrigiu, mostra isso
        if cve in gnuc_fixed:
            gnuc_status = ('<span class="badge badge-fixed">corrigido na GNUcego ' +
                           esc(gnuc_fixed[cve]) + '</span>')
        else:
            # se o Debian já marcou como fixed (tem versão), a GNUcego (que segue
            # o mesmo upstream) herda; senão mostra o status do Debian
            gnuc_status = status_badge(status)
        rows += (f'<tr><td>{cve_link}</td>'
                 f'<td>{esc(descr[:160])}{"&hellip;" if len(descr)>160 else ""}</td>'
                 f'<td>{gnuc_status}</td>'
                 f'<td><code>{esc(status)}</code></td></tr>\n')

    if not rows:
        rows = '<tr><td colspan="4">Nenhuma CVE rastreada para este pacote.</td></tr>'

    return f'''<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CVEs — {esc(name)} — GNUcego</title>
<link rel="stylesheet" href="../../packages.css">
</head>
<body>
<header class="topbar">
  <a class="brand" href="../../index.html">&#128230; Pacotes GNUcego</a>
  <form action="../../index.html" method="get">
    <input type="text" name="q" placeholder="Buscar pacote…" value="">
    <button type="submit">Buscar</button>
  </form>
</header>
<main class="wrap">
<p class="breadcrumb"><a href="../../index.html">Pacotes</a> / <a href="../index.html">segurança</a> / <code>{esc(name)}</code></p>
<h1>CVEs de <code>{esc(name)}</code></h1>
<p class="lead">Pacote Debian mapeado: <code>{esc(debname)}</code>. A coluna <strong>Status na GNUcego</strong> indica a situação real na nossa distribuição (quando a GNUcego já corrigiu a CVE, mostra a versão em que entrou); a coluna <strong>Detalhe</strong> mostra o registro do security-tracker do Debian. Fonte: <a href="https://security-tracker.debian.org/tracker/source-package/{debname}">security-tracker do Debian</a>.</p>
<div class="panel">
<table>
<thead><tr><th>CVE</th><th>Descrição</th><th>Status na GNUcego</th><th>Detalhe (Debian)</th></tr></thead>
<tbody>{rows}</tbody>
</table>
</div>
<p class="back"><a href="../index.html">&#8592; Voltar ao rastreamento</a></p>
</main>
<footer>GNUcego &mdash; distribuição GNU/Linux-libre 100% livre (FSDG) &middot; <a href="/">gnucego.org</a></footer>
</body>
</html>
'''


def main():
    only_security = "--only-security" in sys.argv

    out_dir = os.path.join(SITE, "pacotes")
    pkg_out = os.path.join(out_dir, "pkg")
    sec_out = os.path.join(out_dir, "security")
    sec_pkg_out = os.path.join(sec_out, "pkg")
    os.makedirs(pkg_out, exist_ok=True)
    os.makedirs(sec_pkg_out, exist_ok=True)
    write_css(out_dir)

    # ---- parse CVEs ----
    print("Parseando security-tracker do Debian…")
    pkg_cves = parse_cve_list()
    gnuc_with_cves = set()
    for name in GNUC_PACKAGES:
        if pkg_cves.get(debian_pkg_for_gnuc(name)):
            gnuc_with_cves.add(name)

    # ---- páginas de segurança ----
    print("Gerando páginas de segurança…")
    with open(os.path.join(sec_out, "index.html"), "w", encoding="utf-8") as f:
        f.write(render_security_index(pkg_cves))
    for name in sorted(GNUC_PACKAGES):
        with open(os.path.join(sec_pkg_out, f"{name}.html"), "w", encoding="utf-8") as f:
            f.write(render_security_pkg(name, pkg_cves))
    print(f"  segurança ok ({len(GNUC_PACKAGES)} pacotes GNUcego)")

    if only_security:
        print("Somente segurança (--only-security). Concluído.")
        return

    # ---- catálogo ----
    print("Construindo índice de pacotes…")
    idx, names = build_pkg_index()
    print(f"  {len(names)} pacotes")

    json_list = json.dumps(names)
    json_gnuc = json.dumps(sorted(GNUC_PACKAGES))

    with open(os.path.join(out_dir, "index.html"), "w", encoding="utf-8") as f:
        f.write(render_index(names, json_list, json_gnuc))

    print("Gerando páginas por pacote (todos)…")
    n = 0
    for name in names:
        html = render_pkg_page(name, idx)
        if html:
            with open(os.path.join(pkg_out, f"{name}.html"), "w", encoding="utf-8") as f:
                f.write(html)
            n += 1
    print(f"  {n} páginas de pacote")

    print("CONCLUÍDO.")


if __name__ == "__main__":
    main()
