#!/usr/bin/python3
import argparse
import pathlib
import re
import subprocess

ROOT = pathlib.Path(__file__).resolve().parent.parent
PYPROJECT = ROOT / "pyproject.toml"
BACKUP = ROOT / "debian" / ".pyproject.toml.orig"


def get_upstream_version() -> str:
    cmd = ["dpkg-parsechangelog", "-S", "Version"]
    version = subprocess.check_output(cmd, text=True).strip()
    match = re.match(r"^(?:\\d+:)?([^-]+)(?:-.*)?$", version)
    if not match:
        raise ValueError(f"Unexpected changelog version format: {version!r}")
    return match.group(1)


def apply_fixup() -> None:
    text = PYPROJECT.read_text(encoding="utf-8")
    if not BACKUP.exists():
        BACKUP.write_text(text, encoding="utf-8")

    version = get_upstream_version()
    text = re.sub(
        r'^dynamic = \["version"\]\n', f'version = "{version}"\n', text, flags=re.M
    )

    PYPROJECT.write_text(text, encoding="utf-8")


def restore_fixup() -> None:
    if BACKUP.exists():
        PYPROJECT.write_text(BACKUP.read_text(encoding="utf-8"), encoding="utf-8")
        BACKUP.unlink()


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--apply", action="store_true")
    parser.add_argument("--restore", action="store_true")
    args = parser.parse_args()

    if args.apply == args.restore:
        raise SystemExit("Use exactly one of --apply or --restore")

    if args.apply:
        apply_fixup()
        return

    restore_fixup()


if __name__ == "__main__":
    main()
