import os
import sys
import re
import glob


#

def mention(message):
    sys.stderr.write(message + "\n")


def complain(message):
    mention(message)
    sys.exit(1)


def minimum_version(version, min_version, package):
    version = re.sub(r'([0-9.]+).*', r'\1', version)
    version_t = tuple(map(int, version.split('.')))
    min_version_t = tuple(map(int, min_version.split('.')))
    
    if version_t >= min_version_t:
        mention(package + ' found, version ' + version + ", great.")
        return
    
    complain(package + " must be at least version " + min_version + ", found version " + version)


# Confirm settings.py is importable

try:
    from settings import *
except ImportError:
    complain("Could not import the local settings file; are you running the right script?")

# Confirm config/settings.py is importable

try:
    from config.settings import *
except ImportError:
    complain("Could not import the global settings file; double-check the installation.")

# Check the versions of everything

if sys.version_info[:2] < (2, 6):
    complain("Python 2.6 or higher is required, found version " + '.'.join(map(str, sys.version_info)))
else:
    mention("Python version " + '.'.join(map(str, sys.version_info)) + ", great.")

try:
    import numpy
except ImportError:
    complain("Could not import numpy; is it installed?")

minimum_version(numpy.__version__, '1.6', 'numpy')

try:
    import matplotlib
except ImportError:
    complain("Could not import matplotlib; is it installed?")

minimum_version(matplotlib.__version__, '1.1', 'matplotlib')

try:
    import pytz
except ImportError:
    complain("Could not import pytz; is it installed?")

try:
    import psycopg2
except ImportError:
    complain("Could not import psycopg2; is it installed?")

minimum_version(psycopg2.__version__, '2.4.4', 'psycopg2')

try:
    import dateutils
except ImportError:
    complain("Could not import dateutils; is it installed?")

try:
    PROJECTNAME
except NameError:
    complain("Settings file did not include PROJECTNAME defintion.")
else:
    mention("PROJECTNAME is " + PROJECTNAME)

try:
    TIMEZONE
except NameError:
    complain("Settings file did not include TIMEZONE defintion.")
else:
    mention("TIMEZONE is " + TIMEZONE)

try:
    DEVICES
except NameError:
    complain("Settings file did not include DEVICES defintion.")
else:
    mention("DEVICES:")
    for name, devs in DEVICES.iteritems():
        if isinstance(devs, (list, tuple)):
            mention("\t" + name + ": " + ', '.join(devs))
        else:
            mention("\t" + name + ": " + devs)
 
# Make sure we can write to the project directory

if not os.access(PROJECT_PATH, os.W_OK):
    complain("The project directory must be writeable by the user running the script.")
else:
    mention("PROJECT_PATH ("+PROJECT_PATH+") is writeable, great.")

# Confirm database data exists

if PROCESS_MONITOR:
    if not os.access(MONITOR_PATH_NAME, os.R_OK):
        complain("Did not find the " + MONITOR_PATH_NAME + " file at " + MONITOR_PATH_NAME)
    else:
        mention("Monitor file ("+MONITOR_PATH_NAME+") is readable, great.")

if PROCESS_LOGS:

    # Confirm log files exist and are in the right place
    
    if not os.access(LOGS_PATH, os.R_OK):
        complain("Did not find the logs directory at " + LOGS_PATH)
    else:
        mention("Logs directory ("+LOGS_PATH+") is readable, great.")
    
    unzipped = glob.glob(LOGS_PATH + '/*.csv')
    zipped = glob.glob(LOGS_PATH + '/*.csv.gz')
    
    if not (unzipped or zipped):
        complain("Did not find any .csv.gz or .csv files in the logs directory at " + LOGS_PATH)
    
    if glob.glob(LOGS_PATH + '/*.csv.gz') and glob.glob(LOGS_PATH + '/*.csv'):
        complain("There are both .csv.gz and .csv files in the logs directory at " + LOGS_PATH)
    
    if zipped:
        mention("Reading gzipped log files.")
    else:
        mention("Reading regular log files.")

# Confirm sar output exists

if PROCESS_SAR:

    if not glob.glob(SAR_PATH + '/*.sar.txt'):
        complain("Did not find any .sar.txt files in the sar directory at " + SAR_PATH)
    else:
        mention("Files in sar directory (" + SAR_PATH + ") are readable, great.")
    
# Confirm we can connect as the PG superuser

try:
    import util.db
    connection = util.db.connect(usertype='Super')
except psycopg2.OperationalError as e:
    complain("Could not connect to postgres as superuser " + SUPERUSER + ", exception: " + str(e))
else:
    mention("Can connect to databse as postgres superuser " + SUPERUSER + ", great.")