#!/usr/bin/python
#
# Copyright (c) 2008--2012 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public License,
# version 2 (GPLv2). There is NO WARRANTY for this software, express or
# implied, including the implied warranties of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
# along with this software; if not, see
# http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
#
# Red Hat trademarks are not licensed under GPLv2. No permission is
# granted to use or replicate Red Hat trademarks that are incorporated
# in this software or its documentation.
#

import cStringIO

import sys
import os

# quick check to see if you are a super-user.
if os.getuid() != 0:
    sys.stderr.write('ERROR: must be root to execute\n')
    sys.exit(8)

from spacewalk.satellite_tools.disk_dumper import iss
from spacewalk.satellite_tools.syncLib import log2stderr, log2email
from spacewalk.common.rhnTB import Traceback

if os.geteuid() != 0:
    print "This script must be run as root."
    exit()

if __name__ == "__main__":
    try:
        main = iss.ExporterMain()
    except iss.ISSError, isserror:
        #I have the tb get generated in the function that the the error occurred in to minimize
        #the amount of extra crap that shows up in it.
        tb = isserror.tb
        msg = isserror.msg
        log2stderr(-1, isserror.msg)
        log2stderr(4, isserror.tb)
        sys.exit(-1)
    except SystemExit, se:
        sys.exit(se.code)
    except Exception, e:
        log2stderr(-1, "Unhandled Error: %s" % (e.__class__.__name__,))
        tbout = cStringIO.StringIO()
        Traceback(mail=0, ostream=tbout, with_locals=0)
        log2stderr(4, tbout.getvalue())
        sys.exit(-1)

    try:
        main.main()

    except SystemExit, se:
        sys.exit(se.code)

    except iss.ISSError, isserror:
        tb = isserror.tb
        msg = isserror.msg
        iss.handle_error(msg, tb)

        if main.options.email:
            iss.sendMail()

        if main.options.print_report:
            iss.print_report()

        sys.exit(-1)

    except Exception, e:
        log2stderr(-1, "Unhandled Error: %s" % (e.__class__.__name__,))
        #If we get here we want the traceback, even if it's got some useless junk added to it.
        tbout = cStringIO.StringIO()
        Traceback(mail=0, ostream=tbout, with_locals=0)
        log2email(-1, tbout.getvalue())

        if main.options.email:
            iss.sendMail()

        if main.options.print_report:
            iss.print_report()

        sys.exit(-1)

