#!/usr/bin/env python
import sys
import optparse
import logging

from oplogreplay import OplogReplayer
from bson.timestamp import Timestamp

def parse_arguments():
    usage = '%prog [options] source destination'
    parser = optparse.OptionParser(usage=usage)

    parser.add_option('-v', '--verbose', action='store_true',
                      dest='verbose', default=False,
                      help='increase verbosity')

    parser.add_option('--logpath', action='store', type='string',
                      dest='logpath',
                      help='log file to send write to instead of stdout')

    parser.add_option('--skipIndexes', action="store_false",
                      dest="replay_indexes", default=True,
                      help="skip replaying index operations")

    parser.add_option('--timestamp', action='store', type='string',
                      dest='timestamp',
                      help='start oplog-replay from this timestamp forward '
                           '(e.g.: "1339412676,7")')

    (options, args) = parser.parse_args()

    # Validate timestamp.
    if options.timestamp:
        try:
            options.timestamp = convert_timestamp(options.timestamp)
        except ValueError:
            sys.exit("Invalid timestamp value: %s" % options.timestamp)

    if len(args) != 2:
        sys.exit("Missing operands. Run with --help for more information.")
    options.source = args[0]
    options.dest = args[1]

    return options

def convert_timestamp(timestamp_str):
    """ Validates & converts a timestamp string.

    E.g.:
        "1339412676,7" -> Timestamp(1339412676, 7)
        "1339412676" -> Timestamp(1339412676, 0)
    """
    strarr = timestamp_str.split(',')
    if len(strarr) == 1:
        ts = int(strarr[0])
        i = 0
    elif len(strarr) == 2:
        ts = int(strarr[0])
        i = int(strarr[1])
    else:
        raise ValueError("invalid timestamp_str value %r" % timestamp_str)

    return Timestamp(ts, i)

def setup_logging(options):
    """ Setup basic logging. """
    level = logging.DEBUG if options.verbose else logging.INFO
    format = '%(asctime)s [%(levelname)s] %(message)s'
    # Fri Jun  8 11:52:14
    datefmt = '%a %b %d %X'

    if options.logpath:
        logging.basicConfig(filename=options.logpath, format=format,
                            datefmt=datefmt, level=level)
    else:
        logging.basicConfig(format=format, datefmt=datefmt, level=level)

def main():
    options = parse_arguments()

    setup_logging(options)

    # Start OplogReplayer
    oplogreplayer = OplogReplayer(options.source, options.dest,
                                  replay_indexes=options.replay_indexes,
                                  ts=options.timestamp)
    oplogreplayer.start()

if __name__ == '__main__':
    main()
