#! /usr/bin/env python  
# Part of the A-A-P recipe executive: The main function.

# Copyright (C) 2002 Stichting NLnet Labs
# Permission to copy and use this file is specified in the file COPYING.
# If this file is missing you can find it here: http://www.a-a-p.org/COPYING

# Main Python code that executes an A-A-P recipe

import sys
from traceback import print_exc

# Each phase of executing a recipe is done by one module
from DoAddDef import doadddef
from DoArgs import doargs
from DoBuild import dobuild
from DoRead import doread

from Cache import dump_cache
from Error import *
from Sign import sign_write_all
from Util import *
import Global
from Message import *

# Globals
exit_status = 0		    # exit status, default is zero (success)

def error_msg(msg):
    """print an error message and set the exit status to one"""
    global exit_status
    msg_error(msg)
    if exit_status == 0:
	exit_status = 1


def main():
    """
    The main function to execute an A-A-P recipe.
    """
    # We require Python 1.5 or later.
    if sys.version[0] == '1' and string.atoi(sys.version[2]) < 5:
	print "A-A-P requires Python version 1.5 or later."
	sys.exit(1)

    # When started with a relative path and changing directories we still need
    # to be able to find our modules.
    if not os.path.isabs(sys.argv[0]):
	dir, tail = os.path.split(os.path.abspath(sys.argv[0]))
	sys.path.append(dir)

    # Internationalisation inits: setlocale and gettext.
    i18n_init()

    #
    # Do the main work.
    #
    global exit_status

    try:
	# 1. Process the command line arguments.
	Global.cmd_args = doargs()
	if Global.cmd_args.has_option("verbose"):
	    Global.cmd_args.printit()

	# 2. Read the recipe and included recipes.  Assignments and commands
	#    are executed directly, rules and dependencies are stored.
	#    "work" is a Work object with collected items from the recipe.
	work = doread()

	# 3. Add the default rules and dependencies
	doadddef(work)

	# 4. Build each target.
	dobuild(work)

    except SystemExit, r:
	exit_status = r
    except KeyboardInterrupt:
	error_msg(_("Interrupted"))
    except UserError, e:
    	error_msg(e.args)
    except SyntaxError, e:
	error_msg(_("Syntax error:") + str(e))
	print_exc()
    except:
    	error_msg(_("Internal Error"))
	print_exc()

    # Dump entries for the downloaded files.
    dump_cache()

    # Dump the sign files.
    sign_write_all()

    sys.exit(exit_status)


# When executed directly, call the main function.
if __name__ == '__main__':
    main()

# vim: set sw=4 sts=4 tw=79 fo+=l:
