#!/bin/sh

set -eu

SCRIPT=$(cat <<'PYTHON'
from pathlib import Path

from executions.models import Execution
from rekono.settings import CONFIG
from wordlists.models import Wordlist


def repair(entries, field, directory, unique=False):
    """Point every row whose file is missing at the copy that the new home has.

    Args:
        entries: Rows whose file may have been left behind by version 1.x.
        field: Name of the field that keeps the path of the file.
        directory: Directory of the new home where the copies were written.
        unique: Whether the field is unique, so a taken path cannot be assigned again.

    Returns:
        The rows that were pointed at a copy.
    """
    repaired = []
    for entry in entries:
        stored = getattr(entry, field) or ""
        if not stored or Path(stored).is_file():
            continue
        candidate = directory / Path(stored).name
        if not candidate.is_file():
            continue
        model = type(entry)
        if unique and model.objects.filter(**{field: str(candidate)}).exists():
            print(f"{candidate} already belongs to another {model.__name__}, so {stored} was left as it is")
            continue
        try:
            setattr(entry, field, str(candidate))
            entry.save(update_fields=[field])
        except Exception as exception:
            print(f"{stored} could not be pointed at {candidate}: {exception}")
            continue
        repaired.append(entry)
    return repaired


wordlists = repair(
    Wordlist.objects.exclude(checksum__isnull=True)
    .exclude(checksum="")
    .exclude(path__startswith=f"{CONFIG.wordlists}/"),
    "path",
    CONFIG.wordlists,
    unique=True,
)
if wordlists:
    print(f"Recovered {len(wordlists)} wordlist(s) of rekono-kbx in {CONFIG.wordlists}")

reports = repair(
    Execution.objects.exclude(output_file__isnull=True)
    .exclude(output_file="")
    .exclude(output_file__startswith=f"{CONFIG.reports}/"),
    "output_file",
    CONFIG.reports,
)
if reports:
    print(f"Recovered {len(reports)} tool report(s) of rekono-kbx in {CONFIG.reports}")
PYTHON
)

"${UV}" run --no-dev manage.py shell -c "${SCRIPT}"
