#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (C) 2005 Lateef Alabi-Oki
#
# This file is part of Scribes.
#
# Scribes is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# Scribes is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Scribes; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

u"""
Scribes startup script

Determines the correct path to I{Scribes'} data and library files and then 
executes I{Scribes}.

@author: Lateef Alabi-Oki
@organiation: The Scribes Project
@copyright: Copyright © 2005 Lateef Alabi-Oki
@license: GNU GPLv2 or Later
@contact: mystilleef@gmail.com
"""

from sys import argv, exit as sysexit, path as syspath
from os import path, fork

def find_scribes_lib():
	u"""
	Search for I{Scribes'} data files and modules.
	
	This function is called when I{Scribes} is installed in a non-standard
	location. For example:
	
		python setup.py install --home=~/test
		
	The aforementioned command installs I{Scribes} in ~/test. In such instance, 
	this function is called to search for I{Scribes} startup script, library and
	data files to initialize I{Scribes}.
	
	
	@return: path to I{Scribes'} data files and modules
	@rtype: string
	
	"""
	
	head, tail = path.split(path.split(path.abspath(argv[0]))[0])
	
	if tail == 'bin':
		
		libdir = path.join(head, "lib")
		
		if path.exists(libdir):
			
			python_dir = libdir + "/python"
			scribes_lib_dir = path.join(python_dir, "Scribes")

			if path.exists(scribes_lib_dir):
				
				return python_dir
				
			else:
			
				python_dir = libdir + "/python2.4/site-packages"
				scribes_lib_dir = path.join(python_dir, "Scribes")
				
				if path.exists(scribes_lib_dir):
				
					return python_dir
	
	else:
	
		print "File not found"
		sysexit(1)

	return
		
# Fork Scribes' process from its parent

pid = fork()

if pid != 0:
	 
	sysexit(0)
	
# Initialize Scribes.

try:

	from Scribes.main import main

except ImportError:

	syspath.insert(0, find_scribes_lib())
	from Scribes.main import main
		
if __name__ == "__main__":

	main(argv[1:])
