# Copyright (c) 2009 ActiveState Software Inc.
# See http://www.activestate.com/activepython/license/ for licensing
# information.

"""
    pypm.util.activestate
    ~~~~~~~~~~~~~~~~~~~~~
 
    Functions that are specific to ActiveState
"""

import os
from os.path import exists, join, expanduser
import sys
import re
import logging

LOG = logging.getLogger(__name__)

# Business Edition landing page at activestate.com
BE_HOME_PAGE = 'http://www.activestate.com/business_edition'


NAS_DATA_PATH = r'\\nas' if sys.platform.startswith('win') else '/net/nas/data'
def nas_check(configfile):
    """If configfile contains reference to NAS_DATA_PATH, verify that nas is
    mounted locally
    """
    if (configfile and exists(configfile) and
        'NAS_DATA_PATH' in open(configfile).read()):
        nas_languages_path = join(NAS_DATA_PATH, 'languages')
        if not exists(nas_languages_path):
            raise IOError, 'nas is not mounted at {0}'.format(
                NAS_DATA_PATH)
            
    
def get_license_location():
    """Return the ActiveState license file location"""
    try:
        return os.environ['ACTIVESTATE_LICENSE']
    except KeyError:
        try:
            asdir = os.environ['ACTIVESTATE_HOME']
        except KeyError:
            if sys.platform.startswith('win'):
                from applib.location import _get_win_folder
                appdata = _get_win_folder("CSIDL_APPDATA")
                asdir = join(appdata, 'ActiveState')
            elif sys.platform.startswith('darwin'):
                asdir = expanduser('~/Library/Application Support/ActiveState')
            else:
               asdir = expanduser('~/.ActiveState')
        return join(asdir, 'ActiveState.lic')
        
        
def get_be_license_auth():
    """Return the serial no and API password for the user's BE license
    
    Return `None` if none is available/installed.
    """
    licpath = get_license_location()
    if exists(licpath):
        for line in open(licpath):
            if 'ActivePython BE' in line:
                parts = line.split('|')
                fields = {}
                for part in parts:
                    part = part.strip()
                    if '#' in part:
                        key, value = part.split('#')
                        fields[key] = value
                if 'APIPassword' in fields and 'SerialNo' in fields:
                    return fields['SerialNo'], fields['APIPassword']
        LOG.debug('Cannot find a BE license in %s', licpath)
    else:
        LOG.debug('No ActiveState license found on this machine')


def user_has_be_license():
    """Return True if the user has BE license installed
    
    Their BE license may or may not be valid though. This function only
    cares for the *existence* (not *validation*) of the license. Because
    validation happens on the server side and hence we wouldn't know.
    """
    return get_be_license_auth() is not None