#!/usr/bin/python

import os
import sys
import re
import getopt
import pwd
import logging
import logging.handlers

from clquota import (QuotaWrapper,
                     NoSuchPackageException,
                     NoSuchUserException,
                     IncorrectLimitFormatException,
                     InsufficientPrivilegesException,
                     GeneralException,
                     QuotaDisabledException)
from clquota.utils import (print_text,
                           print_csv,
                           print_text_error,
                           print_csv_error)


def check_username_and_convert_to_uid(username=None):
    '''
    Checks if username is valid one and returns UID as string
    '''
    if username.lower() == 'default':
        return '0'
    try:
        uid = pwd.getpwnam(username).pw_uid
        return str(uid)
    except KeyError:
        raise NoSuchUserException(username)

def check_uid(uid=None):
    '''
    Checks if UID is valid one and retuns it as string
    '''
    p = re.compile(r'(\d+)')
    pm = p.search(uid)
    if not pm:
        raise NoSuchUserException(uid)
    uid = pm.group(1)
    if uid == '0': # this is default. No need to check further
        return uid
    try:
        pwd.getpwuid(int(uid))
    except KeyError:
        raise NoSuchUserException(uid)
    return uid


def setup_system_log():
    """
    Sets syslog logger and returns its handler
    """
    logger = logging.getLogger('clquota')
    logger.setLevel(logging.INFO)
    syslogger = logging.handlers.SysLogHandler(address='/dev/log')
    formatter = logging.Formatter(fmt='%(name)s:%(levelname)s %(message)s')
    syslogger.setFormatter(formatter)
    logger.addHandler(syslogger)
    return logger


def usage():
    print ''
    print 'Usage: ' + sys.argv[0] + ' [OPTIONS]'
    print 'If no options given prints guota statistics for all users'
    print 'Options:'
    print ''
    print ' -u | --user           : specifies the user'
    print ' -U | --user-id        : specifies the user ID'
    print (' -S | --soft-limit     : sets the soft limit for a user. '
          'Pass 0 to cancel soft limit')
    print (' -H | --hard-limit     : sets the hard limit for a user. '
           'Pass 0 to cancel hard limit')
    print ' -V | --csv            : returns data as comma separated values'
    print ' -p | --package        : specifies a package to set or get limits'
    print ' -P | --package-limits : prints package limits'
    print (' -Y | --sync           : synchronizes packages and users limits with'
           ' the database')
    print (' -C | --cache-content  : cache quota data to a file'
           ' the database')
    print ''


def main():
    config = {}
    config['soft']        = None
    config['hard']        = None
    config['user']        = None
    config['user-id']     = None
    config['format']      = 'text'

    output_dispatcher = {
        'text': print_text,
        'csv': print_csv,
        'err_text': print_text_error,
        'err_csv': print_csv_error
    }


    try:
        opts, args = getopt.getopt(sys.argv[1:],
            'PVYCp:u:U:S:H:',
            ['package-limits', 'csv', 'package=', 'user-id=', 'user=',
                'soft-limit=', 'hard-limit=', 'sync', 'cache'])
    except getopt.GetoptError:
        usage()
        sys.exit(1)

    for o, a in opts:
        if o in ['-P', '--package-limits']:
            config['package'] = None
        if o in ['-p', '--package']:
            config['package'] = a
        if o in ['-u', '--user']:
            config['user'] = a
        if o in ['-U', '--user-id']:
            config['user-id'] = a
        if o in ['-S', '--soft-limit']:
            config['soft'] = a
        if o in ['-H', '--hard-limit']:
            config['hard'] = a
        if o in ['-Y', '--sync']:
            config['sync'] = True
        if o in ['-C', '--cache']:
            config['cache'] = True
        elif o in [ '-V',  '--csv' ]:
            config['format'] = 'csv'

    

    try:
        # We don't want to do anything if no saved data
        if 'sync' in config and 'cache' in config:
            if not os.path.exists(QuotaWrapper.DATAFILE):
                return
            q = QuotaWrapper()
            q.synchronize()
            q.save_user_cache()
            return
    
        q = QuotaWrapper()
        if ('package' in config and not (config['soft'] or config['hard'])):
            if config['package'] is None:
                output_dispatcher[config['format']](
                    q.get_all_packages_limits(), title='package')
            else:
                output_dispatcher[config['format']](
                    q.get_package_limits(config['package']), title='package')
            return

        uid = None
        if config['user']:
            uid = check_username_and_convert_to_uid(config['user'])
        elif config['user-id']:
            uid = check_uid(config['user-id'])

        if (config['soft'] or config['hard']):
            if 'package' in config and config['package'] is not None:
                q.set_package_limit(
                    package=config['package'],
                    soft=config['soft'],
                    hard=config['hard'])
                return
            q.set_user_limit(uid=uid, soft=config['soft'], hard=config['hard'])
            return
        if 'sync' in config:
            q.synchronize()
            return
        if 'cache' in config:
            q.save_user_cache()
            return
        if uid:
            output_dispatcher[config['format']](q.get_user_limits(uid),
                title='id', sort_key=int)
        else:
            output_dispatcher[config['format']](q.get_all_users_limits(),
                title='id', sort_key=int)
    except (NoSuchPackageException, NoSuchUserException,
                InsufficientPrivilegesException, IncorrectLimitFormatException,
                GeneralException, QuotaDisabledException), e:
            output_dispatcher['err_'+config['format']](e)
            setup_system_log().info(e)
    except Exception, e:
        setup_system_log().error(e)


if __name__ == '__main__':
    main()
