#!/usr/bin/env python
#
# Usage: % list2dbm listfile
# (produces listfile.db and friends)
#
# Convert a tab-delimited TMDA list file (as text) into a DBM db.
#
# List files should have an e-mail address in the first column,
# and an optional overriding action in the second.  e.g,
#
# foo@mastaler.com
# bar@mastaler.com bounce

import anydbm
import fileinput
import glob
import os
import string
import sys
import tempfile

listfile = sys.argv[1]
dbmname = listfile + '.db'
tempfile.tempdir = os.curdir
tmpname = tempfile.mktemp()

dbm = anydbm.open(tmpname,'n')
for line in fileinput.input(listfile):
    line = string.strip(line)
    if line == '' or line[0] in '#':
        continue
    else:
        line = string.expandtabs(line)
        line = string.split(line, ' #')[0]
        line = string.strip(line)
    linef = string.split(line)
    key = linef[0]
    key = string.lower(key)
    try:
        value = linef[1]
    except IndexError:
        value = ''
    dbm[key] = value

fileinput.close()
dbm.close()

for f in glob.glob(tmpname + '*'):
    newf = string.replace(f,tmpname,dbmname)
    os.rename(f, newf)
