#!/usr/bin/env python
#############################################################################
#
# Linux Desktop Testing Project http://ldtp.freedesktop.org
# 
# ldtprunner
#
#  Author:
#     A. Nagappan <nagappan@gmail.com>
# 
#  Copyright 2005 - 2006 Novell, Inc.
# 
#  This program is free software; you can redistribute it and/or
#  modify it under the terms of the GNU Lesser 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
#  Lesser General Public License for more details.
# 
#  You should have received a copy of the GNU Lesser General Public
#  License along with this program; if not, write to the
#  Free Software Foundation, Inc., 59 Temple Place - Suite 330,
#  Boston, MA 02111-1307, USA.
#
#############################################################################

import sys, re, os, commands
import xml.dom.minidom

if len (sys.argv) < 2:
    print 'Syntax: gldap <XML File>'
    sys.exit (1)
try:
    if sys.argv[1] == '--help' or sys.argv[1] == '-h':
        print 'Syntax: gldap <XML File>'
        sys.exit (1)
except IndexError:
    print 'Syntax: gldap <XML File>'
    sys.exit (1)    

try:
    dom = xml.dom.minidom.parse (sys.argv[1])
except xml.parsers.expat.ExpatError, msg:
    print 'XML Error: ' + str (msg)
    sys.exit (1)
except IOError:
    print 'XML \"' + sys.argv[1] + '\" file not found'
    sys.exit (1)

def getText (nodelist):
    rc = ""
    for node in nodelist:
        if node.nodeType == node.TEXT_NODE:
            rc = rc + node.data
    return rc

import ldtp, ldtputils, traceback

def executeldtp (ldtpxmldata):
    ldtpxml = ldtpxmldata.getElementsByTagName ("ldtp")
    if ldtpxml == []:
        ldtp.log ('ldtp xml tag not present')
        print 'ldtp xml tag not present'
        sys.exit (1)
    logfileappend = 1
    logfilename = ''
    for ldtpelements in ldtpxml:
        try:
            logfileoverwrite = ldtpelements.getElementsByTagName ("logfileoverwrite")[0]
            logfileupdate = getText (logfileoverwrite.childNodes)
            try:
                logfileappend = int (logfileupdate)
            except ValueError:
                # print 'Log file append status not integer value - ' + logfileupdate
                log ('Log file append status not integer value - '
                     + logfileupdate, 'warning')
                None
            # print 'Log append - ' + logfileappend
        except IndexError:
            # print 'Log file overwrite not present'
            None
        try:
            logfile = ldtpelements.getElementsByTagName ("logfile")[0]
            logfilename = getText (logfile.childNodes)
	    if logfilename[0] == "~":
                logfilename = os.path.expanduser (logfilename)
	    elif logfilename[0] == ".":
                logfilename = os.path.abspath (logfilename)
            ldtp.startlog (logfilename, int (logfileappend))
            # print 'Log file name - ' + logfilename + ' - overwrite - ' + str (int (logfileappend))
        except IndexError:
            # print 'Log file entry not present'
            None
        try:
            appmapfile = ldtpelements.getElementsByTagName ("appmapfile")[0]
            appmapfilename = getText (appmapfile.childNodes)
	    if appmapfilename[0] == "~":
                appmapfilename = os.path.expanduser (appmapfilename)
	    elif appmapfilename[0] == ".":
                appmapfilename = os.path.abspath (appmapfilename)
            # print 'Appmap file name: ' + appmapfilename
            ldtp.log ('appmap file name ' + appmapfilename, 'info')
            ldtp.initappmap (appmapfilename)
        except IndexError:
            # print 'Log file entry not present'
            None
        except ldtp.LdtpExecutionError, msg:
            # print 'appmap could not be initalize ' + str (msg)
            ldtp.log ('Appmap could not be initalized ' + str (msg), 'error')
        try:
            executegroup (ldtpelements)
        except KeyboardInterrupt:
            return
    if logfilename != '':
        ldtp.stoplog ()

def executegroup (ldtpelements):
        groups = ldtpelements.getElementsByTagName ("group")
        i = 1
        for groupelements in groups:
            comment = None
            testcaseid = None
            try:
                testcaseid = groupelements.getElementsByTagName ("testcaseid")[0]
            except IndexError:
                # print 'Script file entry not present - skipping'
                ldtp.log ('testcaseid entry not present - skipping', 'warning')
            try:
                comment = groupelements.getElementsByTagName ("comment")[0]
            except IndexError:
                # print 'Script file entry not present - skipping'
                ldtp.log ('comment entry not present - skipping', 'warning')
            # print 'Executing group ' + groupelements.nodeName + str (i)
            ldtp.log ('Executing ' + groupelements.nodeName + str (i), 'groupstart')
            try:
                executescript (groupelements)
            except ldtp.LdtpExecutionError:
                if testcaseid != None:
                    ldtp.log (getText (testcaseid.childNodes), 'testcaseid')
                if comment != None:
                    ldtp.log (getText (comment.childNodes), 'comment')
            except KeyboardInterrupt:
                ldtp.log ('Executing ' + groupelements.nodeName + str (i), 'groupend')
                raise KeyboardInterrupt ()
            ldtp.log ('Executing ' + groupelements.nodeName + str (i), 'groupend')
            i = i + 1

def executescript (groupelements):
    scripts = groupelements.getElementsByTagName ("script")
    scriptPassCount = 0
    totalScripts = len (scripts)
    for scriptelements in scripts:
        scriptname = ''
        scriptdata = ''
        try:
            name = scriptelements.getElementsByTagName ("name")[0]
        except IndexError:
            # print 'Script file entry not present - skipping'
            ldtp.log ('Script file entry not present - skipping', 'warning')
            continue
        scriptname = getText (name.childNodes)
        try:
            data = scriptelements.getElementsByTagName ("data")[0]
            scriptdata = getText (data.childNodes)
        except IndexError:
            ldtp.log ('Data file maynot be present')
        scriptglobal = dict ({'datafilename' : ''})
        if scriptdata != '':
            ldtp.log (scriptname, 'scriptstart')
            ldtp.log (scriptdata, 'datafilename')
            scriptglobal = dict ({'datafilename' : scriptdata})
        else:
            ldtp.log (scriptname, 'scriptstart')
            ldtp.log ('data xml tag missing', 'warning')
        # print 'Executing script: ' + scriptname + ' - ' + scriptdata
        try:
            appmapfile = scriptelements.getElementsByTagName ("appmapfile")[0]
            appmapfilename = getText (appmapfile.childNodes)
	    if appmapfilename[0] == "~":
                appmapfilename = os.path.expanduser (appmapfilename)
	    elif appmapfilename[0] == ".":
                appmapfilename = os.path.abspath (appmapfilename)
            # print 'Appmap file name: ' + appmapfilename
            ldtp.log ('appmap file name ' + appmapfilename, 'info')
            ldtp.initappmap (appmapfilename)
        except IndexError:
            # print 'Log file entry not present'
            None
        except ldtp.LdtpExecutionError, msg:
            # print 'appmap could not be initalize ' + str (msg)
            ldtp.log ('Appmap could not be initalized ' + str (msg), 'error')
        try:
	    if scriptname[0] == "~":
                scriptname = os.path.expanduser (scriptname)
	    elif scriptname[0] == ".":
                scriptname = os.path.abspath (scriptname)
            execfile (scriptname, scriptglobal)
        except ldtp.LdtpExecutionError, ErrorMsg:
            msg = str (ErrorMsg)
            # Escape single quotes and dobule quotes
            replacequotes = re.compile ('\'\"')
            msg = replacequotes.sub ('', msg)
            # print msg
            ldtp.log ('stopping this group execution', 'error')
            ldtp.log (msg, 'cause')
            ldtp.log (scriptname, 'scriptend')
            break
        except IOError:
            ldtp.log ('Script \"' + scriptname + '\" not found', 'error')
            ldtp.log (scriptname, 'scriptend')
            break
        except KeyboardInterrupt:
            #ldtp.log (scriptname, 'scriptend')
            raise KeyboardInterrupt ()
        except:
            ldtp.log (traceback.format_exc (), 'error')
            ldtp.log (scriptname, 'scriptend')
            break
        ldtp.log (scriptname, 'scriptend')
        scriptPassCount = scriptPassCount + 1
    ldtp.log (str (scriptPassCount) + ' test scripts passed of ' +
              str (totalScripts), 'groupstatus')
    if scriptPassCount != totalScripts:
        raise ldtp.LdtpExecutionError ('One or more test scripts failed !')

def enable_accessibility():
    global old_accessibility_value
    old_accessibility_value = commands.getoutput('gconftool-2 --get ' +
                                                 '/desktop/gnome/interface'+
                                                 '/accessibility')
    if old_accessibility_value == 'true':
        return # accessibility is enabled
    
    if commands.getstatusoutput ('gconftool-2 --set --type bool /desktop/gnome'
                                 + '/interface/accessibility true')[0] != 0:
        raise ldtp.LdtpExecutionError ('Accessibility not enabled')
    
def replace_accessibility():
    global old_accessibility_value
    if old_accessibility_value == 'true':
        return
    if commands.getstatusoutput ('gconftool-2 --set --type bool /desktop/gnome'
                                 + '/interface/accessibility false')[0] != 0:
        raise ldtp.LdtpExecutionError ('Unable to reset Accessibility')    
    

sys.path = sys.path + ['.']
old_accessibility_value = 'false'
os.chdir (os.getcwdu ())
enable_accessibility()
executeldtp (dom)
replace_accessibility()
