#!/usr/bin/env python
"""
Set up the evennia system. A first startup consists of giving
the command './manage syncdb' to setup the system and create
the database. 
"""

import sys
import os

# Tack on the root evennia directory to the python path.
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

#------------------------------------------------------------
# Get Evennia version
#------------------------------------------------------------
try:
    VERSION = open("%s%s%s" % (os.pardir, os.sep, 'VERSION')).readline().strip()
except IOError:
    VERSION = "Unknown version"

#------------------------------------------------------------
# Check so session file exists in the current dir- if not, create it. 
#------------------------------------------------------------

_CREATED_SETTINGS = False    
if not os.path.exists('settings.py'):
    # If settings.py doesn't already exist, create it and populate it with some
    # basic stuff.

    settings_file = open('settings.py', 'w')
    _CREATED_SETTINGS = True

    string = \
    """# 
# Evennia MU* server configuration file
#
# You may customize your setup by copy&pasting the variables you want
# to change from the master config file src/settings_default.py to
# this file. Try to *only* copy over things you really need to customize
# and do *not* make any changes to src/settings_default.py directly.
# This way you'll always have a sane default to fall back on
# (also, the master config file may change with server updates).
#

from src.settings_default import * 

###################################################
# Evennia base server config 
###################################################

###################################################
# Evennia Database config 
###################################################

###################################################
# Evennia in-game parsers
###################################################

###################################################
# Default command sets 
###################################################

###################################################
# Typeclasses 
###################################################

###################################################
# Batch processors 
###################################################

###################################################
# Game Time setup
###################################################

###################################################
# In-game access
###################################################

###################################################
# In-game Channels created from server start
###################################################

###################################################
# External Channel connections
###################################################

###################################################
# Config for Django web features
###################################################

###################################################
# Evennia components
###################################################
"""

    settings_file.write(string)
    settings_file.close()

    # obs - this string cannot be under i18n since settings didn't exist yet.
    print """
    Welcome to Evennia (version %(version)s)! 
    We created a fresh settings.py file for you.""" % {'version': VERSION} 


#------------------------------------------------------------
# Test the import of the settings file
#------------------------------------------------------------
try:
    # i18n
    from django.utils.translation import ugettext as _
    from game import settings
except Exception:
    import traceback
    string = "\n" + traceback.format_exc()
    string += _("""\n
    Error: Couldn't import the file 'settings.py' in the directory 
    containing %(file)r. There are usually two reasons for this: 
    1) You moved your settings.py elsewhere. In that case move it back or 
       create a link to it from this folder. 
    2) The settings module is where it's supposed to be, but contains errors.
       Review the traceback above to resolve the problem, then try again. 
    3) If you get errors on finding DJANGO_SETTINGS_MODULE you might have 
       set up django wrong in some way. If you run a virtual machine, it might be worth
       to restart it to see if this resolves the issue. Evennia should not require you 
       to define any environment variables manually. 
    """) % {'file': __file__}
    print string 
    sys.exit(1)

os.environ['DJANGO_SETTINGS_MODULE'] = 'game.settings'

#------------------------------------------------------------
# This is run only if the module is called as a program
#------------------------------------------------------------
if __name__ == "__main__":

    # checks if the settings file was created this run 
    if _CREATED_SETTINGS: 
        print _("""
    Edit your new settings.py file as needed, then run
    'python manage syncdb' and follow the prompts to
    create the database and your superuser account.
        """)
        sys.exit()

    # run the standard django manager, if dependencies match
    from src.utils.utils import check_evennia_dependencies    
    if check_evennia_dependencies():
        from django.core.management import execute_manager    
        execute_manager(settings)
