#!/usr/bin/python
import os
import sys
import pprint
from django.core.management import setup_environ

# personal data
USER = 'vyvyan'
EMAIL = 'Vyvyan Basterd@bbc.com'
PASSWORD = 'SPG'


# preparing environment
PROJECT = sys.argv[1]
CWD = os.getcwd()

PROJECT_ROOT = '%s/%s' % (CWD, PROJECT)
PYTHON_PATH = '%s/%s/src' % (CWD, PROJECT)
SRC_PATH = '%s/%s/src/%s' % (CWD, PROJECT, PROJECT)

sys.path.append(PYTHON_PATH)


# replacement values for settings 
my_settings = dict(
    ADMINS = ((USER, EMAIL),),
    TIME_ZONE = 'Europe/London',
    DATABASE_ENGINE = 'sqlite3',
    DATABASE_NAME = '%s/%s.db' % (PROJECT_ROOT, PROJECT),
    MEDIA_ROOT = '%s/media_root' % PROJECT_ROOT,
    MEDIA_URL = '/media_root',
    TEMPLATE_DIRS = ('%s/templates' % PROJECT_ROOT,),
    )


# creating project dirctories
os.mkdir(PROJECT_ROOT)
sub_dir = ('src', 'site_media', 'templates', 'media_root',
    'site_media/images', 'site_media/css', 'site_media/js')
for d in sub_dir:
    os.mkdir('%s/%s' % (PROJECT_ROOT, d))


# run startproject
os.chdir(PYTHON_PATH)
os.system('django-admin.py startproject %s' % PROJECT)


# rewrite settings.py
settings = __import__('%s/settings' % PROJECT)

for k, v in my_settings.items():
    setattr(settings, k, v)
# enabling admin app 
setattr(settings, 'INSTALLED_APPS', settings.INSTALLED_APPS + ('django.contrib.admin',))


settings_file = '%s/settings.py' % SRC_PATH
pp = pprint.PrettyPrinter(indent=4, width=50)
f = file(settings_file, 'w')
for attr in dir(settings):
    if not attr.startswith('__'):
        f.write('%s = ' % attr)
        f.write(pp.pformat(getattr(settings, attr)))
        f.write('\n\n')
f.close()


# running snycdb
os.chdir(SRC_PATH)
os.system('python manage.py syncdb --noinput')


#setting up django env
setup_environ(settings)


# creating superuser
from django.contrib.auth.models import User
u = User.objects.create_user(USER, EMAIL, PASSWORD)
u.is_staff = True
u.is_active = True
u.is_superuser = True
u.save()
print "Superuser created successfully."


# enabling admin in urls.py
urls = '%s/urls.py' % SRC_PATH
content = ''
f = file(urls)
for line in f:
    if line.find('admin/') >=0:
        content += line[2:]
    else:
        content += line
f.close()
f = file(urls, 'w')
f.write(content)
f.close()