#!/bin/bash

APPLE_DRIVER_BUNDLE="com.apple.driver.AppleUSBFTDI"
FTDI_DRIVER_BUNDLE="com.FTDI.driver.FTDIUSBSerialDriver"

SYSTEM_DRIVER_PATH=/System/Library/Extensions
THIRD_PARTY_DRIVER=/Library/Extensions

FTDI_DRIVER_PATH="FTDIUSBSerialDriver.kext"

echo "1. Listing available drivers"
kextfind -b -is ftdi

echo ""
echo "2. Listing loaded drivers"
kextstat | grep -i ftdi

echo ""
echo "3. Ensuring the correct drivers are loaded"
DRIVERS_LOADED=`kextstat | grep -i ftdi | wc -l`

if [ ${DRIVERS_LOADED} -eq 0 ]
then
    echo "  No drivers found. Is your cable plugged in?"
    exit 1;
fi

FTDI_LOADED=`kextstat | grep -i "${FTDI_DRIVER_BUNDLE}"`
if [ ! -z "${FTDI_LOADED}" ]
then
    echo "  FTDI drivers are loaded. Will unload them"
    sudo kextunload -b ${FTDI_DRIVER_BUNDLE}
else
    echo "  FTDI drivers were not loaded"
fi

echo ""
echo "4. Attempting to remove FTDI driver"
if [ -d "${THIRD_PARTY_DRIVER}/${FTDI_DRIVER_PATH}" ]
then
    echo "  Removing FTDI drivers"
    sudo rm -rf "${THIRD_PARTY_DRIVER}/${FTDI_DRIVER_PATH}"
else
    echo "  No FTDI drivers found"
fi

APPLE_LOADED=`kextstat | grep -i "${APPLE_DRIVER_BUNDLE}"`
if [ -z "${APPLE_LOADED}" ]
then
    echo ""
    echo "5. Loading Apple's FTDI driver"
    sudo kextload -b ${APPLE_DRIVER_BUNDLE}
fi

echo "Done."
