#!/usr/bin/env python
import os
import sys
import getopt
import exceptions
import mc_bin_client
import memcacheConstants

DEFAULT_PORT = "11210"
DEFAULT_HOST_PORT = ["127.0.0.1", DEFAULT_PORT]

def usage(err=0):
    print >> sys.stderr, """

Usage: %s [-h %s[:%s]] [-f filename] [-c]

""" % (os.path.basename(sys.argv[0]),
       DEFAULT_HOST_PORT[0], DEFAULT_HOST_PORT[1])
    sys.exit(err)

def parse_args(args):
    host_port = DEFAULT_HOST_PORT
    filename = ''
    finish = 0
    status = 0

    try:
        opts, args = getopt.getopt(args, 'h:f:c', ['help', 'host=', 'finish', 'file='])
    except getopt.GetoptError, e:
        usage(e.msg)

    for (o, a) in opts:
        if o == '--help':
            usage()
        elif o == '-h' or o == '--host':
            host_port = a.split(':')
            if len(host_port) < 2:
                host_port = [a, DEFAULT_PORT]
        elif o == '-f' or o == '--file':
            filename = a
        elif o == '-c' or o == '--finish':
            finish = 1
        else:
            usage("unknown option - " + o)

    if len(filename) == 0 and finish == 0:
        usage("You need to specify one operation")

    return host_port, filename, finish

if __name__ == '__main__':
    global mc
    host_port, filename, finish = parse_args(sys.argv[1:])

    mc = mc_bin_client.MemcachedClient(host_port[0], int(host_port[1]))

    try:
        if len(filename) > 0:
            fnm = os.path.realpath(filename)
            if not os.path.exists(fnm):
                sys.exit("ERROR: no such file: " + filename)
            mc.restore_file(fnm)

        if finish == 1:
            mc.restore_complete()

    except mc_bin_client.MemcachedError as ne:
        sys.exit("ERROR: " + str(ne))


    finally:
        if mc:
           mc.close()

