#! /usr/bin/env python
import os , sys, getopt

MOBYLEHOME = None
if os.environ.has_key('MOBYLEHOME'):
    MOBYLEHOME = os.environ['MOBYLEHOME']
if not MOBYLEHOME:
    sys.exit('MOBYLEHOME must be defined in your environment')

if ( MOBYLEHOME ) not in sys.path:
    sys.path.append( MOBYLEHOME )
if ( os.path.join( MOBYLEHOME , 'Src' ) ) not in sys.path:    
    sys.path.append( os.path.join( MOBYLEHOME , 'Src' ) )

from Mobyle.Validator import Validator
from Mobyle.Registry import registry

if __name__ == '__main__':

    def usage():
        print """
        Usage: mobvalid [OPTION]... FILE... 
        Validate Mobyle program description files, each FILE being the path to the file.
    
        option:
            -h or --help  ... Print this message and exit.
        """

    # ===== command line parser
    try:
        opts, args = getopt.gnu_getopt( sys.argv[1:], "h", ["help"] )
    
        for option , value in opts: 
    
            if option in ( "-h","--help" ):
                usage()
                sys.exit( 0 )
    
        if not args:
            usage()
            sys.exit( 1 )
            
    except getopt.GetoptError:
            print usage()
            sys.exit( 1 )
    
    for file in args :
      print "Processing file %s..." % (str(file))
      try:
          val = Validator(file)
          val.run()
          if val.valOk:
              print "%s validates." % str(file)
              for re in val.rngErrors:
                  print " - %s" % re
          else:
              print "%s does NOT validate. Details follow:" % str(file)
          if val.runRNG and val.rngOk==False:
              print "* relax ng validation failed."
              for re in val.rngErrors:
                   print " - %s" % re
          if val.runSCH and len(val.schErrors)>0:
              print "* schematron validation failed - errors detail:"
              for se in val.schErrors:
                  print " - %s" % se
      except Exception, e:
          print "Error processing file %s: %s" % (str(file),str(e))
