"""Restore media/ from the archive taken on 24 Aug.

The media directory was deleted from the app root at some point after the
25th, along with the virtualenv. The tarball is still sitting beside it,
so this puts the images back. Where the archive's top level sits decides
whether it extracts into the app root or into media/ itself.
"""

import os
import tarfile

APP = "/home/abmtgrou/en.tupyfittings.com"
TAR = os.path.join(APP, "media-images-2026-08-24.tar.gz")
report = []

with tarfile.open(TAR) as tf:
    names = tf.getnames()
    top = sorted({n.split("/")[0] for n in names if n and not n.startswith(".")})
    report.append("members: %d" % len(names))
    report.append("top level: %r" % top[:8])
    report.append("sample: %r" % names[:4])

    if top == ["media"]:
        dest = APP
    else:
        dest = os.path.join(APP, "media")
        if not os.path.isdir(dest):
            os.makedirs(dest)
    report.append("extracting into: %s" % dest)

    try:
        tf.extractall(dest, filter="data")
    except TypeError:
        tf.extractall(dest)

m = os.path.join(APP, "media")
report.append("media exists: %s" % os.path.isdir(m))
if os.path.isdir(m):
    report.append("media contains: %r" % sorted(os.listdir(m))[:15])
    b = os.path.join(m, "brand")
    report.append("brand exists: %s" % os.path.isdir(b))
    if os.path.isdir(b):
        report.append("brand files: %r" % sorted(os.listdir(b))[:15])

out = "\n".join(report)
open(os.path.join(APP, "restore-media.out"), "w").write(out + "\n")
print(out)