#!/usr/bin/python3
# Get vid:pid for a /dev/dri/card* device
import subprocess
import argparse
from glob import glob
import sys

parser = argparse.ArgumentParser(
        description="Get vid:pid for /dev/dri/card* device or the reverse.")
parser.add_argument("-c", action="store", help="Path to card")
parser.add_argument("-r", action="store", help="Path to render device")
parser.add_argument("-i", action="store", help="vid:pid for card")
args = parser.parse_args()


def get_ids(card):
    """ Get the vid:pid """
    # Get the parent device for the card
    path = subprocess.run(
            ["udevadm", "info", "--query=path", f"--name={card}"],
            check=False, capture_output=True
            ).stdout.decode('utf-8').split("/drm")[0]

    # Get the vid:pid of the gpu
    ids = subprocess.run(
            ["udevadm", "info", "--query=property",
             "--property=PCI_ID", "--value",
             f"--path={path}"],
            check=False, capture_output=True
            ).stdout.decode('utf-8').rstrip().lower()
    return ids


def get_card(ids, path):
    """ Get the path to the card """
    # Iterate through cards to find the matching vid:pid
    for card in glob(path):
        if ids == get_ids(card):
            return card
    return None


# Return info to user based on input
if args.c:
    print(get_ids(args.c))
elif args.i:
    print(get_card(args.i, "/dev/dri/card*"))
elif args.r:
    print(get_card(args.r, "/dev/dri/renderD*"))
else:
    print("Please supply either an ID or card path.")
    sys.exit(1)
