"""Archive the WordPress site so its content can be pulled out later.

The switch to Django only changed .htaccess - every WordPress file is still
in /home/abmtgrou/tupyfittings.com. This packages them up.

Two things are deliberately left out: the 'static' and 'media' symlinks I
added, which point into the Django app and would otherwise be followed and
duplicate hundreds of megabytes into the archive.

The database is NOT included here - dump that from cPanel's Backup page,
which needs no credentials.
"""

import os
import re
import tarfile

SRC = "/home/abmtgrou/tupyfittings.com"
OUT = "/home/abmtgrou/wordpress-backup-2026-09-01.tar.gz"
SKIP = {"static", "media"}
report = []

# which database does WordPress use? (name only - no credentials read)
db = "unknown"
try:
    cfg = open(os.path.join(SRC, "wp-config.php"), "r", errors="replace").read()
    m = re.search(r"define\(\s*['\"]DB_NAME['\"]\s*,\s*['\"]([^'\"]+)", cfg)
    if m:
        db = m.group(1)
except Exception as e:
    report.append("could not read wp-config: %r" % e)
report.append("WordPress database name: %s" % db)

def keep(ti):
    parts = ti.name.split("/")
    if len(parts) > 1 and parts[1] in SKIP:
        return None
    if ti.issym() or ti.islnk():
        return None
    return ti

n = 0
with tarfile.open(OUT, "w:gz") as tf:
    for root, dirs, files in os.walk(SRC):
        rel = os.path.relpath(root, SRC)
        if rel == ".":
            dirs[:] = [d for d in dirs if d not in SKIP]
        for f in files:
            p = os.path.join(root, f)
            if os.path.islink(p):
                continue
            try:
                tf.add(p, arcname=os.path.join("tupyfittings.com-wordpress", os.path.relpath(p, SRC)))
                n += 1
            except Exception:
                pass

size = os.path.getsize(OUT)
report.append("files archived: %d" % n)
report.append("archive: %s" % OUT)
report.append("size: %.1f MB" % (size / 1048576.0))

out = "\n".join(report)
open("/home/abmtgrou/en.tupyfittings.com/wp-backup.out", "w").write(out + "\n")
print(out)