from iam_syncr.errors import SyncrError, BadConfiguration, InvalidConfiguration, NoConfiguration
from iam_syncr.amazon.base import Amazon
from iam_syncr.syncer import Sync
from iam_syncr import VERSION

from rainbow_logging_handler import RainbowLoggingHandler
import argparse
import logging
import fnmatch
import yaml
import sys
import os

log = logging.getLogger("iam_sync.executor")

def setup_logging(verbose=False):
    log = logging.getLogger("")
    handler = RainbowLoggingHandler(sys.stderr)
    handler._column_color['%(asctime)s'] = ('cyan', None, False)
    handler._column_color['%(levelname)-7s'] = ('green', None, False)
    handler._column_color['%(message)s'][logging.INFO] = ('blue', None, False)
    handler.setFormatter(logging.Formatter("%(asctime)s %(levelname)-7s %(name)-15s %(message)s"))
    log.addHandler(handler)
    log.setLevel([logging.INFO, logging.DEBUG][verbose])

    logging.getLogger("boto").level = logging.CRITICAL

def argparse_readable_folder(value):
    """Argparse type for a readable folder"""
    if not os.path.exists(value):
        raise argparse.ArgumentTypeError("{0} doesn't exist".format(value))
    if not os.path.isdir(value):
        raise argparse.ArgumentTypeError("{0} exists but isn't a folder".format(value))
    if not os.access(value, os.R_OK):
        raise argparse.ArgumentTypeError("{0} exists and is a folder but isn't readable".format(value))
    return os.path.abspath(value)

def make_parser():
    """Make us a parser"""
    parser = argparse.ArgumentParser(description="Sync script, supply your own creds!")
    parser.add_argument("-v", "--verbose"
        , help = "Show debug logging"
        , action = "store_true"
        )

    parser.add_argument("folder"
        , help = "The folder containing the roles we want to sync"
        , type = argparse_readable_folder
        )

    parser.add_argument("--accounts-location"
        , help = "Path to accounts.yaml holding the map of human names to accounts ids"
        )

    parser.add_argument("--filename-match"
        , help = "A glob to match the path of the configuration against (relative to the specified folder)"
        , default = "*.yaml"
        )

    parser.add_argument("--only-consider"
        , help = "Only sync these (i.e. roles, remove_roles, users)"
        , action = "append"
        )

    parser.add_argument("--dry-run"
        , help = "Print out what policies would be set/removed"
        , action = "store_true"
        )

    return parser

def accounts_from(location):