#!/usr/bin/env python3

import argparse
import glob
import os.path
import sys


def _main():
    argparser = argparse.ArgumentParser(
        description="Remove USB devices programmatically."
    )
    argparser.add_argument(
        "VIDPID",
        help="Vendor and product ID, e.g. '17ef:6009'",
        metavar="VendorID:ProductID",
    )
    args = argparser.parse_args()

    target_vid, target_pid = args.VIDPID.split(":")

    vid_file_paths = glob.glob("/sys/bus/usb/devices/*/idVendor")
    for vid_file_path in vid_file_paths:
        if vid_file_path.startswith("/sys/bus/usb/devices/usb"):
            # Not interested in root hubs
            continue

        sysfs_path = os.path.dirname(vid_file_path)
        pid_file_path = os.path.join(sysfs_path, "idProduct")
        with open(pid_file_path, encoding="ascii") as pid_file:
            pid = pid_file.read().strip()
        with open(vid_file_path, encoding="ascii") as vid_file:
            vid = vid_file.read().strip()

        if (vid, pid) != (target_vid, target_pid):
            # Not the target device.
            continue

        with open(
            os.path.join(sysfs_path, "removable"), encoding="ascii"
        ) as removable_file:
            is_removable = removable_file.read().strip() in ("fixed", "removable")

        if not is_removable:
            print(
                f"error: device {target_vid}:{target_pid} is not removable",
                file=sys.stderr,
            )
            return 1

        with open(
            os.path.join(sysfs_path, "remove"), "w", encoding="ascii"
        ) as remove_file:
            remove_file.write("1\n")

    return 0


if __name__ == "__main__":
    sys.exit(_main())
