#!/usr/bin/python

import os
import optparse
import time

from sugar import mime

# to use the script in a ssh session
os.environ['DBUS_SESSION_BUS_ADDRESS']='unix:path=/tmp/olpc-session-bus'

def wait_datastore_service_process():
    keep_scanning_proc = True
    ret_pid = None
    while keep_scanning_proc:
        for pid in os.listdir("/proc/"):
            try:
                pid = int(pid)
            except:
                continue

            try:
                cmd = file("/proc/%d/cmdline" % pid).readline()
            except:
                continue
            if cmd.find('datastore-service') > 0:
                keep_scanning_proc = False
                ret_pid = pid
                break

        time.sleep(0.2)

    return ret_pid


def create_journal_object(path):
    from sugar.datastore import datastore
    path__, file_name = os.path.split(path)
    dsobj = datastore.create()
    dsobj.metadata['title'] = str(file_name)
    dsobj.metadata['mime_type'] = mime.get_for_file(path)
    dsobj.file_path = os.path.abspath(path)
    datastore.write(dsobj)
    dsobj.destroy()
    
def datastore_complete_indexing():
    from sugar.datastore import datastore
    datastore.complete_indexing()
    
def main():

    option_parser = optparse.OptionParser(usage="usage: %prog -s sources_dir -b bytes")
    option_parser.add_option("-t", "--test-file", dest="testfile",
                             help="The temporary test file to be copied into the datastore during the test.", default="/tmp/fill_ds_testfile.rand")
    option_parser.add_option("-b",
                             "--bytes", dest="bytes",
                             help="Total number of bytes the new objects in the journal should occupy")
    option_parser.add_option("-s",
                             "--filesize", dest="filesize",
                             help="Filesize of the file to copy into the datastore.  You may use any size specifier allowable by head --bytes=, e.g. b, kB, K, MB, M, etc.  See head --help for a full specification.")

    options, args = option_parser.parse_args()

    if not options.bytes:
        print 'Please specify the number of bytes the new objects should occupy'
        return 1

    new_objs_size = int(options.bytes)

    # generate a random file of size options.filesize
    import os, stat
    os.system("cat /dev/urandom | head --bytes %s >%s" % 
            (options.filesize, options.testfile))
    testfile_bytes = os.stat(options.testfile)[stat.ST_SIZE]
    copy_times =  new_objs_size / testfile_bytes 
    extra_bytes = new_objs_size % testfile_bytes
    extra_file = options.testfile + ".extra"
    if extra_bytes:
        os.system("cat /dev/urandom | head --bytes %i >%s" %
                (extra_bytes, extra_file))

    resp = raw_input(" ! Please restart sugar and press a key.\n >> ")
    print ' - ok. waiting for the datastore-service process to start ..'
    # block until the datastore-service is running
    ds_pid = wait_datastore_service_process()
    print '  (found with pid: ' + str(ds_pid) + ')'

    # we must wait a bit here or we traceback in dbus
    time.sleep(0.1)
    start_time = time.time()
    print '\n * starting test ...'
    for i in range(0, copy_times):
        print "writing file", i
        create_journal_object(options.testfile)
    if extra_bytes:
        print "writing extra file"
        create_journal_object(extra_file)
    complete_indexing_time = time.time()
    
    # cleanup
    os.remove(options.testfile)
    if extra_bytes:
        os.remove(extra_file)

    print ' - new objs created in '+ str(complete_indexing_time - start_time) + 's'
    print ' - complete_indexing() took '+ str(time.time() - complete_indexing_time) + 's'
    # we must wait a bit here or we traceback in xapianindex.py
    time.sleep(0.2)
    print ' * sending SIGHUP to datastore-service !'
    command = 'kill -s HUP ' + str(ds_pid)
    os.system(command)

main()
