#!/usr/bin/env python3
import argparse
import os
import shutil
from pathlib import Path


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(
        description="Copies a resource subtree into the macOS app bundle."
    )
    parser.add_argument("--source", required=True)
    parser.add_argument("--dest", required=True)
    return parser.parse_args()


def copy_tree(src: Path, dst: Path, active_dirs: set[Path]) -> None:
    resolved_src = src.resolve()

    if resolved_src.is_dir():
        if resolved_src in active_dirs:
            raise RuntimeError(f"Refusing to recurse into symlink loop at {src}")

        active_dirs.add(resolved_src)
        dst.mkdir(parents=True, exist_ok=True)
        for child in sorted(resolved_src.iterdir()):
            copy_tree(child, dst / child.name, active_dirs)
        active_dirs.remove(resolved_src)
        return

    dst.parent.mkdir(parents=True, exist_ok=True)
    shutil.copy2(resolved_src, dst)


def main() -> None:
    args = parse_args()

    destdir_prefix = os.environ["MESON_INSTALL_DESTDIR_PREFIX"]
    source = Path(args.source)
    dest = Path(destdir_prefix) / args.dest

    copy_tree(source, dest, set())


if __name__ == "__main__":
    main()
