#!/usr/bin/env python
# encoding: utf-8
"""
backupmodelstofixtures.py

TARBALL DATABASE FIXTURE DUMPER.

Created by FI$H 2000 on 2010-04-18.
Copyright (c) 2010 OST, LLC.
MIT License. It works, bitches.

Usage: fill in the blanks, run it, and collect your tarballed fixtures.

Tested by me on Debian and Mac OS -- it works in Textmate or from
the prompt. It will tell you what it is doing. On the Mac, it will
use /usr/bin/open -R to courteously reveal the finished tarball
in the Finder once it is done. 

An enterprising Django fan could easily kill five minutes making it
into a management command.
"""

from __future__ import with_statement

import sys
from django.core.management import setup_environ
import settings
setup_environ(settings)

import os, tarfile, shutil
from datetime import datetime
from tempfile import mkdtemp, gettempdir
from django.core.management.commands.dumpdata import Command as Dumper
from django.core.management.base import CommandError

# some typical off-the-shelf models:
from django.contrib.auth.models import User
from django.contrib.sessions.models import Session
from tagging.models import Tag, TaggedItem

# fill your models in here.
from your_project.some_app import AModel, AnotherModel
from your_project.some_other_app import AndStillYetAnotherModel

# format the models as a dict, 
# to match up with the management
# command 'app.model' syntax
appstogo = dict(
	auth=(User,),
	sessions=(Session,),
	admin=(ContentType,LogEntry),
	some_app=(AModel,AnotherModel),
	some_other_app=(AndStillYetAnotherModel,)
	# etc.
)

# it comes out like: 20100923-052013.tgz --
# they will chronologically sort themselves in a file listing.
timestamp = datetime.strftime(
	datetime.now(),
	"%Y%m%d-%H%M%S",
)

# change this to what you prefer and/or what your OS demands
#finaldestination = "/home/you"
finaldestination = "/Users/you/Desktop"

fixdir = mkdtemp(prefix='', suffix=timestamp)
fixtarfilename = "%s.tar.gz" % timestamp
fixtarname = os.path.join(gettempdir(), fixtarfilename)
fixtar = tarfile.open(fixtarname, "w:gz")
os.chdir(fixdir)

print "> Dumping model fixtures to temporary directory %s" % fixdir

print ""
for app, modls in appstogo.items():
	for modl in modls:
		try:
			fix = Dumper.handle(Dumper(), "%s.%s" % (app, modl.__name__.lower()), format='json', indent=4)
		except CommandError, message:
			print "# dumpdata raised a CommandError: %s" % message
		else:
			fixname = "%s_%s.json" % (app, modl.__name__.lower())
			print "+ Dumping all instances of %s to %s..." % (modl.__name__, fixname)
			with open(os.path.join(fixdir, fixname), "w+") as fixh:
				fixh.write(fix)

print ""
print "> Creating fixture archive in %s..." % fixtarname
for fixxx in os.listdir(fixdir):
	fixtar.add(fixxx, recursive=False)
fixtar.close()

print ""
print "> Cleaning up..."
for dirty in os.listdir(fixdir):
	os.remove(dirty)
os.rmdir(fixdir)


print "> Moving fixture archive to %s..." % finaldestination
shutil.move(fixtarname, finaldestination)

if os.path.exists('/usr/bin/open'):
	print "> Revealing..."
	os.system('/usr/bin/open -R %s' % os.path.join(finaldestination, fixtarfilename))


print "> Done."


sys.exit(0)