#!/usr/bin/env python
# -*-python-*-

"""
Backup tool for Couchbase.

"""

import sys
import os
import time
import subprocess

if len(sys.argv) < 3:
    if os.name == 'posix':
        sys.exit('\n'.join([r'usage: %(prog)s [bucket_path_name] [dest_dir_path]',
                        r'examples:',
                        r'   %(prog)s /opt/couchbase/var/lib/couchbase/data/default-data/default /backups/2010-10-31/'])
             % {'prog': sys.argv[0]})
    elif os.name == 'nt':
        sys.exit('\n'.join([r'usage: %(prog)s [bucket_path_name] [dest_dir_path]',
                        r'examples:',
                        r'   %(prog)s "c:/program files/couchbase/server/var/lib/couchbase/data/default-data/default" c:/backups/2010-10-31/'])
             % {'prog': sys.argv[0]})

def backup(sqlite_path, srcdir, destdir, fn):
    done = False
    sleep_time = 12
    src_path_name = os.path.join(srcdir, fn)
    if os.path.exists(src_path_name):
        while not done:
            pb = subprocess.Popen([sqlite_path, src_path_name,
                                  '.backup "%s" ' % os.path.join(destdir, fn)])
            pb.communicate()
            if pb.returncode != 0:
                print "Try backup %s again" % fn
                time.sleep(sleep_time)
                done = False
            else:
                print "Backup of %s done" % fn
                pv = subprocess.Popen([sqlite_path, os.path.join(destdir, fn),
                                      'vacuum'])
                pv.communicate()
                print "Vacuum of %s done" % fn
                done = True

def findCmd(cmdName):
    cmd_dir = os.path.dirname(sys.argv[0])
    possible = []
    for bin_dir in [cmd_dir, os.path.join(cmd_dir, "..", "..", "bin")]:
        possible = possible + [os.path.join(bin_dir, p) for p in [cmdName, cmdName + '.exe']]
    cmdbin = [p for p in possible if os.path.exists(p)][0]
    return cmdbin

def find_sqlite():
    return findCmd('sqlite3')

src_path, dest_path = sys.argv[1:]
sqlite_path = find_sqlite()

for n,p in [('src', src_path), ('dest', dest_path)]:
    if not os.path.exists(p):
        sys.exit("ERROR: %s does not exist at %s" % (n, p))

dirname, bucket_name = os.path.split(src_path)

backup(sqlite_path, dirname, dest_path, bucket_name)
for ext in ['.sqlite', '.mb']:
    for i in range(4):
        backup(sqlite_path, dirname, dest_path, '%s-%d%s' % (bucket_name, i, ext))

