#!/usr/bin/env python
import sys
if sys.platform != 'darwin':
    raise SystemExit("{} runs on Mac OS X only".format(sys.argv[0]))

from subprocess import check_output, CalledProcessError

if check_output(['sw_vers', '-productVersion']).strip() >= '10.9.0':
    modules = ['com.apple.driver.AppleUSBFTDI',
               'com.FTDI.driver.FTDIUSBSerialDriver']
    unload_cmd = 'kextunload -bundle-id'
else:
    modules = ['/System/Library/Extensions/FTDIUSBSerialDriver.kext']
    unload_cmd = 'kextunload'

print("Unloading the OS FTDI driver. This may require the sudo password")
errors = False
for module in modules:
    try:
        check_output(['sudo'] + unload_cmd.split() + [module])
    except CalledProcessError as e:
        errors = True
        print("Failed to unload {}:".format(module))
        print(e)
    else:
        print("Unloaded {}".format(module))

if errors:
    raise SystemExit("Command failed")
