#!/bin/bash
# Parche voluntario del archivo de datos de Shadow of Mordor.
# Reconstruye el tramo desde otra copia de la textura presente en el juego.
_mordor_udun() {
    python3 - "$1" "$MG_ROMS" "$MG_DIR/backups/mordor-udun" <<'MG_MORDOR_PY'
"""Validate PC Shadow of Mordor LTAR v3 archives without changing them."""
import argparse
import os
from pathlib import Path
import struct
import zlib


HEADER = struct.Struct("<4sIIII")
ENTRY = struct.Struct("<IQQQI")
CHUNK = struct.Struct("<II")
PATHS_OFFSET = 48
MAX_CHUNK = 65536


def validate(path, selected_resource):
    # The LTAR layout is documented by the MordorFormats reader.
    with path.open("rb", buffering=1024 * 1024) as archive:
        size = os.fstat(archive.fileno()).st_size
        magic, version, names_size, _, entry_count = HEADER.unpack(archive.read(HEADER.size))
        if magic != b"LTAR" or version != 3:
            raise ValueError("se esperaba un archivo LTAR v3 de Shadow of Mordor para PC")

        table_end = PATHS_OFFSET + names_size + entry_count * ENTRY.size
        if table_end > size:
            raise ValueError("la tabla de recursos excede el tamaño del archivo")

        archive.seek(PATHS_OFFSET)
        names = archive.read(names_size)
        entries = sorted(ENTRY.iter_unpack(archive.read(entry_count * ENTRY.size)), key=lambda row: row[1])
        resources = 0
        chunks = 0
        for name_offset, start, packed_size, decoded_size, _ in entries:
            name_end = names.find(b"\0", name_offset)
            if name_end < 0:
                raise ValueError("nombre de recurso fuera de la tabla")
            name = names[name_offset:name_end].decode("utf-8", errors="replace")
            if selected_resource is not None and name.casefold() != selected_resource.casefold():
                continue

            resources += 1
            end = start + packed_size
            if end > size or (packed_size and start < table_end):
                raise ValueError(f"{name}: datos fuera del área de recursos")
            remaining = decoded_size
            offset = start
            while remaining:
                archive.seek(offset)
                header = archive.read(CHUNK.size)
                if len(header) != CHUNK.size:
                    raise ValueError(f"{name}, offset {offset}: cabecera incompleta")
                packed, decoded = CHUNK.unpack(header)
                context = f"{name}, offset {offset}"
                if not (0 < packed <= decoded <= min(MAX_CHUNK, remaining)):
                    raise ValueError(f"{context}: tamaños de bloque inválidos ({packed}, {decoded})")
                if offset + CHUNK.size + packed > end:
                    raise ValueError(f"{context}: el bloque excede su recurso")
                payload = archive.read(packed)
                if len(payload) != packed:
                    raise ValueError(f"{context}: bloque incompleto")
                if packed < decoded:
                    decoder = zlib.decompressobj()
                    try:
                        output = decoder.decompress(payload, decoded + 1)
                    except zlib.error as error:
                        raise ValueError(f"{context}: zlib rechazó el bloque ({error})") from error
                    if len(output) != decoded or not decoder.eof or decoder.unused_data:
                        raise ValueError(f"{context}: flujo zlib incompleto o longitud incorrecta")
                offset = start + ((offset - start + CHUNK.size + packed + 3) & ~3)
                remaining -= decoded
                chunks += 1

        if resources == 0:
            raise ValueError(f"no se encontró el recurso {selected_resource!r}")
        return resources, chunks


"""Reconstruct the known damaged Shadow of Mordor archive into a separate file."""
import argparse
import hashlib
import os
from pathlib import Path
import shutil
import struct
import tempfile
import zlib



REGION_START = 4_795_404_288
REGION_END = 4_795_662_336
ORIGINAL_SIZE = 5_337_719_732
DAMAGED_SHA = "076e5e6c2a2bebabf8938cac9d73947e85bd07583aa453434eeccb1f9ac00673"
REPAIRED_SHA = "2f4ab63896dcc5d0583a273adb49430220cc71680192968bebfbb06b26546283"
BLOCK_SHA = "7ea445f1b60a05d2dc1d89b9cacb458f1255872e519da1c3e3e395c9c1afd675"
TEXTURE = r"materials\blackgates\detail\shantygarbage01_d.tex"


def read_at(file, offset, size):
    file.seek(offset)
    data = file.read(size)
    if len(data) != size:
        raise ValueError(f"lectura incompleta en el offset {offset}")
    return data


def read_donor_texture(path):
    # Locate the original texture in the other region, without extracting game data to disk.
    with path.open("rb", buffering=1024 * 1024) as archive:
        header = struct.unpack("<4s4I", read_at(archive, 0, 20))
        magic, version, names_size, _, count = header
        if (magic, version) != (b"LTAR", 3):
            raise ValueError("son.arch05 no usa el formato esperado")
        names = read_at(archive, 48, names_size)
        table = read_at(archive, 48 + names_size, 32 * count)
        bundle = bytearray()
        for index, start, packed, raw, _ in struct.iter_unpack("<IQQQI", table):
            if names[index:names.index(0, index)] == b"feast01.embb":
                break
        else:
            raise ValueError("falta feast01.embb en son.arch05")
        offset = start
        while len(bundle) < raw:
            compressed, size = struct.unpack("<II", read_at(archive, offset, 8))
            if not (0 < compressed <= size <= min(65536, raw - len(bundle))):
                raise ValueError("bloque inválido en son.arch05")
            if offset + 8 + compressed > start + packed:
                raise ValueError("bloque fuera de feast01.embb en son.arch05")
            payload = read_at(archive, offset + 8, compressed)
            decoded = zlib.decompress(payload) if compressed < size else payload
            if len(decoded) != size:
                raise ValueError("tamaño decodificado inesperado en son.arch05")
            bundle.extend(decoded)
            offset = start + ((offset - start + compressed + 11) & ~3)

    magic, version, names_size, table_offset, flags, references, count = struct.unpack_from("<4s6I", bundle)
    if (magic, version, flags) != (b"BNDL", 4, 0):
        raise ValueError("feast01.embb no usa el formato esperado")
    offset = 28 + table_offset + 4 * references
    for _ in range(count):
        index, size = struct.unpack_from("<II", bundle, offset)
        name_start = 28 + index
        name_end = bundle.index(0, name_start, 28 + names_size)
        name = bundle[name_start:name_end].decode("utf-8")
        offset += 8
        if name.casefold() == TEXTURE and size == 1_398_295:
            return bytes(bundle[offset + 17688:offset + 83224])
        offset += size
    raise ValueError("falta la textura compatible en son.arch05")


def recover_region(archive, donor):
    if archive.stat().st_size != ORIGINAL_SIZE:
        raise ValueError("udun.arch05 tiene un tamaño distinto al caso conocido")
    with archive.open("rb") as source:
        region = read_at(source, REGION_START, 262144)
        observed = read_at(source, 4_795_641_948, 25003)
    if hashlib.sha256(region).hexdigest() != DAMAGED_SHA:
        raise ValueError("udun.arch05 no tiene la firma del daño conocido")

    raw = read_donor_texture(donor)
    if len(raw) != 65536 or zlib.adler32(raw) != int.from_bytes(observed[-4:], "big"):
        raise ValueError("la textura no reproduce el checksum original")
    encoder = zlib.compressobj(9, zlib.DEFLATED, 15, 9)
    restored = encoder.compress(raw) + encoder.flush()
    if hashlib.sha256(restored).hexdigest() != BLOCK_SHA:
        raise ValueError("la codificación zlib no reproduce el bloque original")
    if restored[:20388] != observed[:20388] or restored[21412:] != observed[20388:]:
        raise ValueError("el bloque reconstruido difiere en bytes que ya estaban sanos")
    repaired = region[1024:REGION_END - REGION_START] + restored[20388:21412]
    if hashlib.sha256(repaired).hexdigest() != REPAIRED_SHA:
        raise ValueError("la región reconstruida no coincide con la reparación verificada")
    return repaired



import contextlib
import fcntl
import signal
import stat
import subprocess
import sys

TITLE = "Middle Earth Shadow of Mordor"
OUTER_SIZE = 34_198_478_848
OUTER_OFFSET = 28_797_486_135
OLD_REGION_SHA = "3674d4b74fc08a23ff74f85fbb88b6209e2ab8c3489b807ac8ef80d5179ff0e0"
SUPERBLOCK_SHA = "bbd0d31c5c2933cd538b739b97c9214b526ba5777e0a9038a15332a932c59703"
METADATA_SHA = "4c6740da9a63fe1af4ecf8f54636aaccd6e6ad018f3ee80e264195cfcdcb371e"
REGION_SIZE = REGION_END - REGION_START


def sha(data):
    return hashlib.sha256(data).hexdigest()


def offset_for(file, packed):
    size = os.fstat(file.fileno()).st_size
    if not packed:
        if size == ORIGINAL_SIZE and read_at(file, 0, 8) == b"LTAR\x03\x00\x00\x00":
            return REGION_START
        return None

    # This exact package stores the repair in two contiguous uncompressed blocks.
    if size == OUTER_SIZE and sha(read_at(file, 0, 96)) == SUPERBLOCK_SHA:
        if sha(read_at(file, 34_198_384_609, 92_270)) == METADATA_SHA:
            return OUTER_OFFSET
    return None


def journal_path(backups, file, packed):
    info = os.fstat(file.fileno())
    kind = "paquete" if packed else "carpeta"
    return backups / f"{kind}-{info.st_dev}-{info.st_ino}.bin"


def read_journal(path):
    try:
        with path.open("rb") as file:
            data = file.read(REGION_SIZE * 2 + 1)
    except FileNotFoundError:
        return None
    original, patched = data[:REGION_SIZE], data[REGION_SIZE:]
    if len(patched) != REGION_SIZE or sha(original) != OLD_REGION_SHA or sha(patched) != REPAIRED_SHA:
        raise ValueError("el respaldo del parche no coincide")
    return original, patched


def classify(file, offset, journal):
    actual = read_at(file, offset, REGION_SIZE)
    signature = sha(actual)
    if signature == REPAIRED_SHA:
        return "reparado"
    if signature == OLD_REGION_SHA:
        return "afectado"
    if journal:
        original, patched = journal
        boundary = next((i for i, pair in enumerate(zip(actual, patched)) if pair[0] != pair[1]), REGION_SIZE)
        if actual[boundary:] == original[boundary:]:
            return "interrumpido"
    return "desconocido"


def close_game_check(info):
    for command in Path("/proc").glob("[0-9]*/cmdline"):
        try:
            args = command.read_bytes().split(b"\0")
        except OSError:
            continue
        if any(arg.replace(b"\\", b"/").rsplit(b"/", 1)[-1].lower() == b"shadowofmordor.exe" for arg in args):
            raise ValueError("cierra Shadow of Mordor antes de aplicar el parche")
    for entry in Path("/sys/block").glob("loop*/loop/backing_file"):
        try:
            backing = Path(entry.read_text().strip()).stat()
        except OSError:
            continue
        if (backing.st_dev, backing.st_ino) == (info.st_dev, info.st_ino):
            raise ValueError("el paquete del juego sigue montado")


@contextlib.contextmanager
def archive_view(path, packed):
    if not packed:
        yield path
        return
    with tempfile.TemporaryDirectory(prefix="mg-mordor-") as directory:
        subprocess.run(["mount", "-t", "squashfs", "-o", "loop,ro", str(path), directory], check=True)
        try:
            archives = list(Path(directory).rglob("udun.arch05"))
            if len(archives) != 1:
                raise ValueError("el paquete no contiene un udun.arch05 identificable")
            yield archives[0]
        finally:
            subprocess.run(["umount", directory], check=True)


def save_journal(path, original, patched):
    path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
    with tempfile.NamedTemporaryFile(dir=path.parent, delete=False) as file:
        pending = Path(file.name)
        try:
            file.write(original)
            file.write(patched)
            file.flush()
            os.fsync(file.fileno())
            os.link(pending, path)
            directory = os.open(path.parent, os.O_RDONLY | os.O_DIRECTORY)
            try:
                os.fsync(directory)
            finally:
                os.close(directory)
        finally:
            pending.unlink()


def write_region(file, offset, data):
    file.seek(offset)
    if file.write(data) != len(data):
        raise OSError("escritura incompleta")
    file.flush()
    os.fsync(file.fileno())
    if read_at(file, offset, len(data)) != data:
        raise OSError("el tramo escrito no coincide")


def process(path, packed, backups, mode):
    if path.is_symlink() or (not packed and path.parent.is_symlink()):
        return "desconocido"
    with path.open("rb") as file:
        offset = offset_for(file, packed)
        if offset is None:
            return "desconocido"
        journal_file = journal_path(backups, file, packed)
        journal = read_journal(journal_file)
        state = classify(file, offset, journal)
    if mode != "aplicar" or state not in ("afectado", "interrumpido"):
        return state

    fd = os.open(path, os.O_RDWR | os.O_NOFOLLOW)
    with os.fdopen(fd, "r+b", buffering=0) as file:
        fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
        info = os.fstat(fd)
        if not stat.S_ISREG(info.st_mode) or info.st_nlink != 1:
            raise ValueError("el archivo del juego no es una copia independiente")
        if offset_for(file, packed) != offset or journal_path(backups, file, packed) != journal_file:
            raise ValueError("el archivo cambió durante la comprobación")
        journal = read_journal(journal_file)
        state = classify(file, offset, journal)
        if state == "reparado":
            return state
        if state not in ("afectado", "interrumpido"):
            raise ValueError("el archivo ya no coincide con el defecto conocido")
        close_game_check(info)

        if journal is None:
            original = read_at(file, offset, REGION_SIZE)
            with archive_view(path, packed) as archive:
                patched = recover_region(archive, archive.with_name("son.arch05"))
            save_journal(journal_file, original, patched)
        else:
            original, patched = journal

        close_game_check(info)
        if path.stat().st_ino != info.st_ino or path.stat().st_dev != info.st_dev:
            raise ValueError("el archivo cambió antes de aplicar")
        try:
            write_region(file, offset, patched)
            with archive_view(path, packed) as archive:
                if validate(archive, "feast01.embb") != (1, 1623):
                    raise ValueError("el recurso reparado no pasó la validación")
        except BaseException:
            write_region(file, offset, original)
            raise

    print(f"Shadow of Mordor: recurso validado, respaldo en {journal_file}")
    return "reparado"


def interrupted(signum, frame):
    raise InterruptedError(f"parche interrumpido por señal {signum}")


def run(mode, roms, backups):
    signal.signal(signal.SIGTERM, interrupted)
    windows = roms / "windows"
    targets = [(windows / (TITLE + ".pc") / "udun.arch05", False),
               (windows / (TITLE + ".wsquashfs"), True)]
    states = [process(path, packed, backups, mode) for path, packed in targets if path.is_file()]
    pending = any(state in ("afectado", "interrumpido") for state in states)
    if mode == "necesita":
        return 0 if pending else 1
    return 0 if "reparado" in states and not pending else 1


try:
    raise SystemExit(run(sys.argv[1], Path(sys.argv[2]), Path(sys.argv[3])))
except (OSError, ValueError, struct.error, subprocess.CalledProcessError) as error:
    print(f"Shadow of Mordor: {error}", file=sys.stderr)
    raise SystemExit(1)

MG_MORDOR_PY
}

necesita() { _mordor_udun necesita; }
aplicar() { _mordor_udun aplicar; }
comprobar() { _mordor_udun comprobar; }
