# Path: copilot/utils/file_sys.py
# def get_usb_dirs():
#     """ Get the directory for all mounted USB devices.
#     """
#     devices = []
#     log.info("Getting all USB devices.")
#     with open("/proc/partitions") as partitionsFile:
#         lines = partitionsFile.readlines()[2:] #Skips the header lines
#         for line in lines:
#             words = [x.strip() for x in line.split()]
#             minorNumber = int(words[1])
#             deviceName = words[3]
#             if minorNumber % 16 == 0:
#                 path = "/sys/class/block/" + deviceName
#                 if os.path.islink(path):
#                     if os.path.realpath(path).find("/usb") > 0:
#                         devices.append('/dev/'+deviceName)
#     log.debug("USB devices found: {0}".format(devices))
#     log.debug("Getting mount points.")
#     mounts = []
#     for line in subprocess.check_output(['mount', '-l']).split('\n'):
#         parts = line.split(' ')
#         if len(parts) > 2:
#             if parts[0][:-1] in devices:
#                 mounts.append(parts[2])
#     log.debug("USB mount points found: {0}".format(mounts))
#     return mounts
# 
# def get_likely_usb():
#     """ Get the last mounted USB device.
# 
#     Because many devices can have many USB's attached to them
#     this function tries to pick the most likely desired USB.
#     To do this, this function picks the last mounted USB. We
#     hope that a persons tendency to unplug and plug back in
#     a USB when retrying will ensure that this correctly ID's
#     the USB desired.
# 
#     """
#     log.debug("Getting USB device.")
#     all_usb = get_usb_dirs()
#     if len(all_usb) > 0:
#         likely_usb = all_usb[-1]
#         log.debug("Likely USB device {0} found.".format(likely_usb))
#         return likely_usb
#     else:
#         log.debug("No USB devices found.")
# 
# Path: copilot/utils/plugin.py
# def is_plugin(name):
#     """ Check if a string is the name of a plugin.
# 
#     Args:
#         name (str): A possible plugin name
#     """
#     log.debug("Checking if plugin {0} exists".format(name))
#     plugins = get_plugins()
#     if name in plugins:
#         log.debug("plugin {0} exists.".format(name))
#         return True
#     else:
#         log.debug("plugin {0} does not exist.".format(name))
#         return False
# 
# def get_plugins():
#     """ Get a list of available plugins.
# 
#     Gets the basename of each folder name in the plugins directory
#     and returns the list as the list of plugins.
#     """
#     plugin_dir = os.environ['COPILOT_PLUGINS_DIRECTORY'] + "/plugins/"
#     # Get all folder names in plugins directory
#     # remove the directory cruft to make them plugin names
#     plugins = []
#     for item in os.listdir(plugin_dir):
#         if os.path.isfile(os.path.join(plugin_dir, item, "config.py")):
#             plugins.append(item)
#     log.debug("Plugins found: {0}".format(plugins))
#     return plugins


import os, sys
import string
import importlib
import logging
from urlparse import urlparse
from copilot.utils.file_sys import get_usb_dirs, get_likely_usb
from ConfigParser import SafeConfigParser
from copilot.utils.plugin import is_plugin, get_plugins
    Args:
        name (str): The name of the plugin that you want a writer for.
    """
    log.debug("getting configuration writer")
    plugin = import_plugin(name)
    writer = plugin.ConfigWriter()
    return writer

def get_config_dir(directory):
    """Return the appropriate directory for a non-plugin config file.

    Each type of config file is kept in a different location. This
    function identified the correct location for a specific config
    file.

    Args:
        directory (str): The type of config file directory to return.
    """
    log.debug("requesting config directory {0}".format(directory))
    base_directories = {}
    base_directories.setdefault("profiles", os.environ['COPILOT_PROFILE_CONFIG_DIRECTORY'])
    base_directories.setdefault("temporary", os.environ['COPILOT_TEMPORARY_CONFIG_DIRECTORY'])
    base_directories.setdefault("main", os.environ['COPILOT_DEFAULT_CONFIG_DIRECTORY'])
    log.debug("base directories set as {0}".format(base_directories))
    # Test if one of the basic directories
    if directory in base_directories:
        log.debug("directory {0} found in the base directories".format(directory))
        return base_directories.get(directory)
    elif directory == "usb":
        log.debug("directory is a usb directory")

# Path: copilot/utils/file_sys.py
# def get_usb_dirs():
#     """ Get the directory for all mounted USB devices.
#     """
#     devices = []
#     log.info("Getting all USB devices.")
#     with open("/proc/partitions") as partitionsFile:
#         lines = partitionsFile.readlines()[2:] #Skips the header lines
#         for line in lines:
#             words = [x.strip() for x in line.split()]
#             minorNumber = int(words[1])
#             deviceName = words[3]
#             if minorNumber % 16 == 0:
#                 path = "/sys/class/block/" + deviceName
#                 if os.path.islink(path):
#                     if os.path.realpath(path).find("/usb") > 0:
#                         devices.append('/dev/'+deviceName)
#     log.debug("USB devices found: {0}".format(devices))
#     log.debug("Getting mount points.")
#     mounts = []
#     for line in subprocess.check_output(['mount', '-l']).split('\n'):
#         parts = line.split(' ')
#         if len(parts) > 2:
#             if parts[0][:-1] in devices:
#                 mounts.append(parts[2])
#     log.debug("USB mount points found: {0}".format(mounts))
#     return mounts
# 
# def get_likely_usb():
#     """ Get the last mounted USB device.
# 
#     Because many devices can have many USB's attached to them
#     this function tries to pick the most likely desired USB.
#     To do this, this function picks the last mounted USB. We
#     hope that a persons tendency to unplug and plug back in
#     a USB when retrying will ensure that this correctly ID's
#     the USB desired.
# 
#     """
#     log.debug("Getting USB device.")
#     all_usb = get_usb_dirs()
#     if len(all_usb) > 0:
#         likely_usb = all_usb[-1]
#         log.debug("Likely USB device {0} found.".format(likely_usb))
#         return likely_usb
#     else:
#         log.debug("No USB devices found.")
# 
# Path: copilot/utils/plugin.py
# def is_plugin(name):
#     """ Check if a string is the name of a plugin.
# 
#     Args:
#         name (str): A possible plugin name
#     """
#     log.debug("Checking if plugin {0} exists".format(name))
#     plugins = get_plugins()
#     if name in plugins:
#         log.debug("plugin {0} exists.".format(name))
#         return True
#     else:
#         log.debug("plugin {0} does not exist.".format(name))
#         return False
# 
# def get_plugins():
#     """ Get a list of available plugins.
# 
#     Gets the basename of each folder name in the plugins directory
#     and returns the list as the list of plugins.
#     """
#     plugin_dir = os.environ['COPILOT_PLUGINS_DIRECTORY'] + "/plugins/"
#     # Get all folder names in plugins directory
#     # remove the directory cruft to make them plugin names
#     plugins = []
#     for item in os.listdir(plugin_dir):
#         if os.path.isfile(os.path.join(plugin_dir, item, "config.py")):
#             plugins.append(item)
#     log.debug("Plugins found: {0}".format(plugins))
#     return plugins


# Path: copilot/models/config.py
import os, sys
import string
import importlib
import logging
from urlparse import urlparse
from copilot.utils.file_sys import get_usb_dirs, get_likely_usb
from ConfigParser import SafeConfigParser
from copilot.utils.plugin import is_plugin, get_plugins

    Args:
        name (str): The name of the plugin that you want a writer for.
    """
    log.debug("getting configuration writer")
    plugin = import_plugin(name)
    writer = plugin.ConfigWriter()
    return writer

def get_config_dir(directory):
    """Return the appropriate directory for a non-plugin config file.

    Each type of config file is kept in a different location. This
    function identified the correct location for a specific config
    file.

    Args:
        directory (str): The type of config file directory to return.
    """
    log.debug("requesting config directory {0}".format(directory))
    base_directories = {}
    base_directories.setdefault("profiles", os.environ['COPILOT_PROFILE_CONFIG_DIRECTORY'])
    base_directories.setdefault("temporary", os.environ['COPILOT_TEMPORARY_CONFIG_DIRECTORY'])
    base_directories.setdefault("main", os.environ['COPILOT_DEFAULT_CONFIG_DIRECTORY'])
    log.debug("base directories set as {0}".format(base_directories))
    # Test if one of the basic directories
    if directory in base_directories:
        log.debug("directory {0} found in the base directories".format(directory))
        return base_directories.get(directory)
    elif directory == "usb":
        log.debug("directory is a usb directory")

        return get_likely_usb()