import sys
import argparse
from os.path import exists
from systools import sleep_with_countdown, find_bus_path, driver_path, bind, unbind

if __name__ == "__main__":
    # TODO: check for root
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument("vendor", help="vendor id (or vendor:product)")
    parser.add_argument("product", help="product id", nargs="?")
    args = parser.parse_args()
    if not args.product:
        if ":" in args.vendor:
            args.vendor, args.product = args.vendor.split(":", 1)
        else:
            sys.exit("vendor product or vendor:product")

    syspath, systag = find_bus_path(bus="usb", idVendor=args.vendor, idProduct=args.product)
    driver = driver_path(syspath)
    assert exists(driver)
    print syspath
    raw_input("Press RETURN to unbind, sleep 5, and rebind: ")
    print "Unbinding", systag
    unbind(driver, systag)
    sleep_with_countdown(5)
    print "Rebinding", systag
    bind(driver, systag)
    sleep_with_countdown(3)
    print "DONE (but unchecked)"
        pci_id = args.pci_id
        slots = lspci().keys()
        if pci_id not in slots:
            sys.exit("{} not found in {!r}".format(pci_id, slots))
    elif args.usb2:
        if args.usb3:
            sys.exit("only reset one controller at a time")
        pci_id = lspci_lookup("USB controller", "EHCI") # class 0x0c03
    elif args.usb3:
        if args.usb2:
            sys.exit("only reset one controller at a time")
        pci_id = lspci_lookup("USB controller", "xHCI") # class 0x0c03
    else:
        sys.exit("specify some pci slot")

    full_pci_id = "{}:{}".format(args.pci_bus, pci_id)
    print "id:", full_pci_id
    driver = realpath("/sys/bus/pci/devices/{}/driver".format(full_pci_id))
    print "driver:", driver
    assert os.path.exists(driver), "{} not found".format(driver)
    raw_input("Press RETURN to unbind, sleep 5, and rebind: ")
    print "Unbinding", full_pci_id
    unbind(driver, full_pci_id)
    sleep_with_countdown(5)
    print "Rebinding", full_pci_id
    bind(driver, full_pci_id)
    sleep_with_countdown(3)
    print lspci().get(pci_id, "{} not found after rebind!".format(pci_id))

    # TODO: catch any added lines in kern.log for signs of activity