#!/usr/bin/python
#
# Copyright (C) 2012 Intel Corporation
# 
# This program 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.
#
# This program 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 this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
#
# Authors:
#              Tang, Shaofeng <shaofeng.tang@intel.com>


import os
import re
import sys, traceback
import time
import platform
import ctypes
import glob
import ConfigParser
import xml.etree.ElementTree as etree
from optparse import *
from shutil import copyfile
from tempfile import mktemp
from datetime import datetime
from tctshell.shellwrapper import TestKitShellWrapper
from tctshell.shellrunner import WrapperRunner
from tctshell.shellrunner import Guider


def main():
    wrapper = TestKitShellWrapper()
    wrapper.parse_options(sys.argv)
    runner     = WrapperRunner()
    guider  =  Guider(runner,wrapper.get_sdb_device_id_param())
    plan       = None
    suites     = []
    result_xml = wrapper.get_output_file_name()
    origin_xml = result_xml

    if wrapper.check_sdb_devices() and wrapper.check_sdb_devices_env():
        runner.pull_device_capabilities(wrapper)
        runner.pull_build_info(wrapper)
        runner.pull_preconfigure_json(wrapper)
        guider.init_items()
        if wrapper.options.testplan_file is not None:
            print "ExecuteTestPlan: %s" % wrapper.options.testplan_file[0]
            plan = wrapper.options.testplan_file[0]
        elif wrapper.is_suite_mode():
            print "ExecuteTestSuites:"
            suites = wrapper.get_suites()
        if wrapper.options.fail_result_xml is not None:
            origin_xml = os.path.abspath(wrapper.options.fail_result_xml[0])
            guider.set_conf_path(os.path.dirname(origin_xml))

        if not runner.prepare_testplan(plan, wrapper.running_mode, suites, origin_xml):
            sys.exit(1)

        print "is_enable_preconf_func: ", wrapper.is_enable_preconf_func()
        if wrapper.is_enable_preconf_func():
            guider.setup_env()

        runner.execute_suite_in_loop(wrapper,guider)

        runner.merge_suite_result(result_xml, wrapper.get_plan_name())

        if wrapper.is_fail_rerun_mode():
            runner.merge_result_xml(origin_xml, result_xml)

        runner.copy_result_xml(result_xml)
        runner.copy_preconfigure_file()

        wrapper.print_result_summary(result_xml)
        runner.open_report(wrapper)


if __name__ == "__main__":
    main()

