#!/usr/bin/env python

import getopt
import os
import sqlite3
import sys

CONF_FILE = '/etc/sysconfig/cloudlinux-fchange'
DB_TABLE = 'log'
PROTOCOL_VERSION = 1


def get_db_file():
    with open(CONF_FILE) as r:
        for line in r:
            if line.startswith('#') or '=' not in line:
                continue
            key, value = [i.strip() for i in line.split('=', 1)]
            if key == 'database_path':
                return value
    return '/var/lve/cloudlinux-fchange.db'


def get_data(timestamp, uid):
    db_file = get_db_file()

    if not os.path.exists(db_file):
        sys.exit('No database file found')

    try:
        with sqlite3.connect(db_file) as conn:
            res = conn.execute(
                'SELECT DISTINCT uid, filename, ('
                'SELECT MAX(timestamp) FROM %s '
                'WHERE (uid = ? or ? = "ALL") and timestamp >= ?'
                ') AS latest_timestamp FROM %s '
                'WHERE (uid = ? or ? = "ALL") and timestamp >= ? '
                'ORDER BY timestamp'
                % (DB_TABLE, DB_TABLE),
                (uid, uid, timestamp, uid, uid, timestamp)
            )

            first_line = True
            for u, f, t in res:
                if first_line:
                    print '%d,%d' % (PROTOCOL_VERSION, t)
                    first_line = False
                try:
                    print '%d:%s' % (u, f.encode('utf-8'))
                except UnicodeEncodeError:
                    pass
    except sqlite3.OperationalError as err:
        sys.exit(err)


def main():
    if os.geteuid() != 0:
        sys.exit('Superuser privileges are required')

    timestamp = 0
    uid = 'ALL'

    try:
        opts, args = getopt.getopt(
            sys.argv[1:],
            'ht:u:',
            [
                'help',
                'timestamp=',
                'uid=',
            ]
        )

        if args:
            raise getopt.GetoptError('argument %s not recognized' % (args[0],))
    except getopt.GetoptError as err:
        print err
        print
        usage()
        sys.exit(1)

    for o, a in opts:
        if o in ['-h', '--help']:
            usage()
            sys.exit(0)
        elif o in ['-t', '--timestamp']:
            if not a.isdigit():
                sys.exit('Timestamp expects to be a number')
            timestamp = int(a)
        elif o in ['-u', '--uid']:
            if not a.isdigit():
                sys.exit('UID expects to be a number')
            uid = int(a)

    get_data(timestamp, uid)


def usage():
    print 'Usage: %s [OPTIONS]' % (sys.argv[0],)
    print ' -t | --timestamp : Only get data after time specified'
    print ' -u | --uid : UID of a user for which files should be retrieved'


if __name__ == '__main__':
    main()
