#!/usr/bin/env python
# file manage by puppet 

import os
import gzip
import tarfile
import datetime
import urllib2
import simplejson
import couchdb.tools.dump
from os.path import join

DB_URL="http://127.0.0.1:5984"
DUMP_DIR="<%= backupdir %>"
TODAY=datetime.datetime.today().strftime("%A").lower()

ftar = os.path.join(DUMP_DIR,"%s.tar" % TODAY)
tmp_ftar = os.path.join(DUMP_DIR,"_%s.tar" % TODAY)
tar = tarfile.open(tmp_ftar, "w")

databases = simplejson.load(urllib2.urlopen("%s/_all_dbs" % DB_URL))

for db in databases:
  db_file = os.path.join(DUMP_DIR,"%s.gz" % db)
  f = gzip.open(db_file, 'wb')
  couchdb.tools.dump.dump_db(os.path.join(DB_URL,db), output=f)
  f.close()
  tar.add(db_file,"%s.gz" % db)
  os.remove(db_file)

tar.close()
os.rename(tmp_ftar,ftar)