#!/usr/bin/python

# This script dumps the contents of message databases built by grokevt-ripdll.
#
# Copyright (C) 2006-2007,2011 Timothy D. Morgan
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation version 3 of the
# License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# vi:set tabsize=4:
# $Id: grokevt-dumpmsgs 119 2011-06-20 17:14:14Z tim $


import sys
import os
import dbm

import grokevt


def usage():
    sys.stderr.write("USAGE:\n")
    sys.stderr.write("  %s <MESSAGE_DB1> [<MESSAGE_DB2> ...]\n\n"\
                     % os.path.basename(sys.argv[0]))
    sys.stderr.write("grokevt-dumpmsgs dumps the contents of message databases\n")
    sys.stderr.write("built previously by grokevt-ripdll.\n")


if len(sys.argv) < 2:
    usage()
    sys.exit(os.EX_USAGE)

for dbfile in sys.argv[1:]:
    if not os.access(dbfile, os.R_OK):
        sys.stderr.write("ERROR: DB file could not be read.")
        sys.exit(1)

    db = dbm.open(dbfile.split('.db', 1)[0], 'r')

    if grokevt.template_encoding == grokevt.output_encoding:
        for key in db.keys():
            print('%s,%s' % (key.decode('ascii'), grokevt.quoteBinary(db[key], b'%,"')))
    else:
        for key in db.keys():
            msg = db[key].decode(grokevt.template_encoding)
            msg = grokevt.quoteBinary(msg.encode(grokevt.output_encoding,'replace'),
                                      b'%,"')
            print('%s,%s' % (key.decode('ascii'), msg))

    db.close()
