#!/usr/bin/python
#
# Chris Lumens <clumens@redhat.com>
#
# Copyright 2005, 2006 Red Hat, Inc.
#
# This software may be freely redistributed under the terms of the GNU
# general public license.
#
# 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., 675 Mass Ave, Cambridge, MA 02139, USA.
#

import optparse
import os
import sys
import warnings
import tempfile
import urlgrabber
import shutil
from pykickstart.data import *
from pykickstart.parser import *

from rhpl.translate import _
import rhpl.translate as translate

translate.textdomain("pykickstart")

def cleanup(destdir, exitval=1):
    shutil.rmtree(destdir)
    os._exit(exitval)

op = OptionParser(usage="usage: %prog [options] ksfile|url")
op.add_option("-e", "--firsterror", dest="firsterror", action="store_true",
              default=False, help=_("halt after the first error or warning"))
op.add_option("-i", "--followincludes", dest="followincludes",
              action="store_true", default=False,
              help=_("parse include files when %include is seen"))

(opts, extra) = op.parse_args(sys.argv[1:])

if len(extra) != 1:
    op.print_help()
    os._exit(1)
else:
    destdir = tempfile.mkdtemp("", "ksvalidator-tmp-", "/tmp")
    f = urlgrabber.urlgrab(extra[0], filename="%s/ks.cfg" % destdir)

ksdata = KickstartData()
kshandlers = KickstartHandlers(ksdata)
ksparser = KickstartParser(ksdata, kshandlers,
                           followIncludes=opts.followincludes,
                           errorsAreFatal=opts.firsterror)

# turn DeprecationWarnings into errors
warnings.filterwarnings("error")

try:
    ksparser.readKickstart(f)
except DeprecationWarning, msg:
    print _("File uses a deprecated option or command.\n%s") % msg
    cleanup(destdir)
except (KickstartParseError, KickstartValueError), msg:
    print msg
    cleanup(destdir)
except KickstartError:
    print _("General kickstart error in input file")
    cleanup(destdir)
except Exception, e:
    print _("General error in input file:  %s") % e
    cleanup(destdir)

cleanup(destdir, exitval=0)
