#!/usr/bin/python

# linda - Replacement for lintian
# (c) 2001-2003 Steve Kowalik <stevenk@debian.org>

# 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

###########################################################

#
# > How *DARE* you interrupt this flame war about useless spam with your 
# > useless spam.
# Hey, doogie, give my brain back.  I need it.
# I think.
#                 -- Branden Robinson
#

###########################################################

import sys, traceback
try:
    import os, pwd, gettext
    from linda import parse_archs, checks, common, output
    from linda.common import set_up_locale, dprint, vprint
    from linda.unpack import real_cull, Unpacker, UnpackException
    from linda.parser import CmdLineParser
except ImportError, e:
    print "Failed to import modules: %s" % e
    print "Please try setting the PYTHONPATH environment variable."
    traceback.print_exc(file=sys.stdout)
    sys.exit(6)

locale_dir = '/usr/share/locale'
gettext.bindtextdomain('linda', locale_dir)
gettext.textdomain('linda')
_ = gettext.gettext

class Linda:
    def __init__(self):
        common.linda_root = os.environ.get('LINDA_ROOT', '/usr/share/linda')

        for z in ('/checks', '/desc', '/output'):
            if not os.path.isdir(common.linda_root + z):
                print _("Linda: %s is not a directory.") % \
                    (common.linda_root + z)
                sys.exit(5)
        set_up_locale()
        parse_archs()
        if os.geteuid() == 0:
            print _("Linda: Running as root, dropping to nobody.")
            os.seteuid(pwd.getpwnam('nobody')[3])
        self.register()

    def register(self):
        output.register_all(common.linda_root + '/output')
        checks.register_all(common.linda_root + '/checks')
        if os.path.isdir(os.path.expanduser('~/.linda/checks')):
            checks.register_all(os.path.expanduser('~/.linda/checks'))
        if os.path.isdir('/etc/linda/checks'):
            checks.register_all('/etc/linda/checks')

    def run(self):
        self.parse_args()
        self.instaniate_output()
        dprint(_("Files: %s") % common.options['files'])
        for file in common.options['files']:
            vprint(_("Processing file: %s") % os.path.split(file)[1], 1)
            dprint(_("Processing file: %s") % os.path.split(file)[1])
            file_mappping = {'dsc': 'source', 'deb': 'binary', 'udeb': 'udeb'}
            throw, ext = os.path.splitext(file)
            if ext == '.changes':
                checks.apply('', file, 'changes', 1)
                continue
            unpack = Unpacker()
            try:
                unpack.unpack(file, 1)
            except UnpackException, e:
                throw, filename = os.path.split(file)
                print _("File %s failed to unpack: %s") % (filename, e)
                if not common.options['no_cull']:
                    unpack.cull_lab()
                continue
            if common.options['unpack_level'] == 0:
                if hasattr(common.out_class, 'file_pre_print'):
                    common.out_class.file_pre_print(file)
                checks.apply(common.options['lab_directory'], file, \
                    file_mappping[ext[1:]], 1)
            if checks.registry[file_mappping[ext[1:]]][2]:
                if common.options['unpack_level'] != 1:
                    try:
                        unpack.unpack(file, 2)
                    except UnpackException, e:
                        throw, filename = os.path.split(file)
                        print _("File %s failed to unpack: %s") % \
                            (filename, e)
                        if not common.options['no_cull']:
                            unpack.cull_lab()
                        continue
                if common.options['unpack_level'] == 0:
                    checks.apply(common.options['lab_directory'], file, \
                        file_mappping[ext[1:]], 2)
            unpack.cull_lab()
            if hasattr(common.out_class, 'file_post_print'):
                common.out_class.file_post_print(file)
        sys.exit(common.exit_status)

    def instaniate_output(self):
        tmp_class = output.registry[common.options['format']]
        common.out_class = tmp_class()

    def parse_args(self):
        parser = CmdLineParser()
        parser.parse_args()

if __name__ == '__main__':
    try:
        linda = Linda()
        linda.run()
    except KeyboardInterrupt:
        if common.options['no_cull'] and common.options['lab_directory']:
            print _("Leaving %s and exiting.") % \
                common.options['lab_directory']
        elif common.options['lab_directory']:
            real_cull(common.options['lab_directory'])
            print _("Removing %s and exiting.") % \
                common.options['lab_directory']
        else:
            print _("Exiting due to user interrupt.")

