#!/usr/bin/python2 -tt
#
# gdbm2db4
# --------
# This is a quick helper script written to convert vadmin preference files
# in existing gdbm format into db4, since it would seem that Centos does not
# come with gdbm dba extension compiled in.
#
# Copyright (c) 2004 by Konstantin Ryabitsev <icon@duke.edu>
# Licensed under the GNU GPL. For full terms see http://www.gnu.org/
#
# $Id: gdbm2db4,v 1.2 2004/07/30 01:09:47 graf25 Exp $
#
# @author Konstantin Ryabitsev <icon@duke.edu> ($Author: graf25 $)
# @version $Date: 2004/07/30 01:09:47 $
#

import os
import sys
import getopt
import gdbm
import bsddb

DEFAULT_CONVERSION_PATH = '/var/lib/vadmin'
GDBMPREFIX = '.db'
DB4PREFIX = '.db4'

def errout(ecode, msg):
    sys.stderr.write('%s\n' % msg)
    sys.exit(ecode)

def getAllDbFiles(path):
    try: allfiles = os.listdir(path)
    except OSError, e: errout(2, e)
    dbfiles = []
    for afile in allfiles:
        if afile[-len(GDBMPREFIX):] == GDBMPREFIX:
            dbfiles.append(afile[:-len(GDBMPREFIX)])
    return dbfiles

def convert(infile, outfile):
    idb = gdbm.open(infile, 'r')
    odb = bsddb.btopen(outfile, 'cw')
    for key in idb.keys(): odb[key] = idb[key]
    idb.close()
    odb.close()
    print "%s -> %s" % (infile, outfile)

def usage(ecode=0):
    print """gdbm2db4 [-p path]
    Convert a directory of gdbm-format files into db4-format files.

    -p path
        Use this path instead of /var/lib/vadmin
    -h or --help
        This help screen.
    """
    sys.exit(ecode)

def main(args):
    path = DEFAULT_CONVERSION_PATH
    try:
        gopts, cmds = getopt.getopt(args, 'p:h', ['help'])
        for o, a in gopts:
            if o == '-p': path = a
            else: usage()
    except getopt.error, e:
        errout(1, e)
    dbfiles = getAllDbFiles(path)
    if not dbfiles:
        errout(0, 'No matching files found in %s' % path)
    for dbfile in dbfiles:
        infile = os.path.join(path, dbfile) + GDBMPREFIX
        outfile = os.path.join(path, dbfile) + DB4PREFIX
        try: convert(infile, outfile)
        except Exception, e:
            print 'Error trying to convert %s. Ignored this file.' % dbfile
    print 'Conversion complete.'

if __name__ == '__main__':
    main(sys.argv[1:])

##
# Local variables:
# mode: python
# end:
