#!/usr/bin/python
# -*- coding: utf-8 -*-
# version: 20110704
# By Dennis Drescher (dennis_drescher at sil.org)


###############################################################################
######################### Description/Documentation ###########################
###############################################################################

# One script to rule them all.  This is the mother script of the whole system.
# This script will drive all processes and keep track of what happens in the
# project log in each respective project.

# History:
# 20110610 - djd - Start initial draft
# 20110704 - djd - Start refactor for multiple component types
# 20110721 - djd - Added proper command line processing
# 20110729 - djd - Removed TIPE system settings from project folder


###############################################################################
################################ Initialize TIPE ##############################
###############################################################################
# Firstly, import all the standard Python modules we need for this process and
# set the base path

import os, sys

# Set the TIPE base program path
tipeHome = os.environ.get('TIPE_BASE')
if not tipeHome :
	tipeHome = os.path.join('usr', 'share', 'xetex-tipe')
	os.environ['TIPE_BASE'] = tipeHome

# Set the user environment path
userHome = os.environ.get('TIPE_USER')
if not userHome :
	sysHome = os.environ.get('HOME')
	userHome = os.path.join(sysHome, '.config', 'tipe')
	os.environ['TIPE_USER'] = userHome

# Set the (potential) project home
projHome = os.getcwd()

# Set our paths to application resources
sys.path.insert(0, os.path.join(tipeHome, 'bin', 'python'))
sys.path.insert(0, os.path.join(tipeHome, 'bin', 'python', 'lib_system'))

# Load standard Python modules
import codecs, shutil, operator
from datetime import *
from configobj import ConfigObj

# Load the local classes
from tools import *
from user_config import UserConfig
from sys_command import Command, commands
from project import Project

# Catch any incoming commands here
command = ""
opts = []

if len(sys.argv) > 1 :
	command = sys.argv[1]
	opts = sys.argv[2:]


###############################################################################
######################## Load User and Project Info ###########################
###############################################################################

# Get all our user config info and methods
uConf = UserConfig(userHome, tipeHome)

# Load in project settings if they exist in the cwd
projConfFile = os.path.join(projHome, '.project.conf')
projType = None

# Now create a fresh projConfig object
if os.path.isfile(projConfFile) :
	# Create a fresh merged version of the projConfig
	projConfig  = mergeProjConfig(ConfigObj(projConfFile), projHome, userHome, tipeHome)

	# If we successfuly created a projConfig, the we will load in the type info.
	# For a project conf file to be written out it must be a valid project type
	# so this next part should not fail.
	if projConfig :
		projectType         = projConfig['ProjectInfo']['projectType']
		tipeProjTypes       = os.path.join(tipeHome, 'resources', 'lib_projTypes')
		projInit            = getProjInitSettings(userHome, tipeHome, projectType)
		from proj_command import *

# FIXME: Need to override sys path with user path if the type exists there
		# Dynamically load the right project type modules
		thisTypeLib = os.path.join(tipeProjTypes, projectType, 'lib_python')
		sys.path.insert(0, thisTypeLib)
		projModule = __import__(projectType)

	else :
		terminal('ERROR: Failed to load: ' + projConfFile)
		# die here

	# Fold in the projConfig into the aProject object
	aProject = getattr(projModule, projectType[0].upper() + projectType[1:], Project)(projConfig, projInit, uConf.userConfig, projHome, userHome, tipeHome)
	recordProject(uConf.userConfFile, projConfig, projHome)

else :
	# If there is no project, we still need a
	# dummy projConfig object so we'll just make one up.
	projConfig  = ConfigObj()
	projInit    = ConfigObj()
	aProject    = Project(projConfig, projInit, uConf.userConfig, projHome, userHome, tipeHome)


###############################################################################
############################### Terminal Startup ##############################
###############################################################################

# Do some cleanup like getting rid of the last sessions error log file.
try :
	if os.path.isfile(aProject.projErrorLogFile) :
		os.remove(aProject.projErrorLogFile)
except :
	pass

# Give a welcome message
terminal('\n\t\tWelcome to TIPE ' + aProject._userConfig['System']['systemVersion'])
terminal('\t\tCurrent User: ' + aProject._userConfig['System']['userName'])
if os.path.isfile(aProject.projConfFile) :
	terminal('\t\tCurrent Project: ' + aProject._projConfig['ProjectInfo']['projectName'] + ' (' + aProject._projConfig['ProjectInfo']['projectIDCode'] + ')')


###############################################################################
##################### Prepare and Process TIPE Commands #######################
###############################################################################

# Run the command and pass along the aProject object
if command :
	if command in commands :
		# To process there should be one or more options
		if len(opts) >= 1 :
			commands[command].run(opts, aProject, uConf.userConfig)
		else :
			# If we seem to be short on options then we will just display the help
			# for this command
				terminal('\nHelp for the \"' + command + '\" command:\n')
				commands['help'].run([command])

	else :
		terminal('\nERROR: This command does not exist: ' + command)

else :
	terminal('\nAvailable commands:')
	commands['help'].run(opts, aProject, uConf.userConfig)


###############################################################################
########################### Closeout TIPE Session #############################
###############################################################################

# Now write out the config files if needed
if aProject.writeOutProjConfFile :
	writeProjConfFile(aProject._projConfig, projHome)
	aProject.writeOutProjConfFile = False

if aProject.writeOutUserConfFile :
	writeUserConfFile(aProject._userConfig, userHome)
	aProject.writeOutUserConfFile = False


## Politely say good bye
terminal('\n\t\tThank you, please come again!\n')

