#!/usr/bin/python

# aa
#
# Project: AutoArchive
# License: GNU GPLv3
#
# Copyright (C) 2003 - 2010 Robert Cernansky
# Copyright (C) 2003 - 2010 HOME software



"""Main file for AutoArchive.
"""



# INCLUDE FILES

import traceback

from AutoArchive.aautils import *
from AutoArchive.options import *
from AutoArchive import archive_spec
from AutoArchive import archiver



# CONSTANTS

# enumerates statuses how can finish the baskup operation
BackupStatuses = Enum(

    # backup operation finished successfully
    "Successful",

    # backup operation finished successfully with some issues
    "Issues",

    # backup operation failed
    "Failed")



# FUNCTIONS

def main():

    # process arguments passed to program
    processArguments(optionParser)

    # process each passed aa file
    success = BackupStatuses.Successful
    for aaFileName in arguments:

        if options.verbose:
            print "Processing %s." % aaFileName

        # process archive spec file
        try:
            spec = archive_spec.ArchiveSpec(aaFileName)
        except Exception, ex:
            printError(str(ex))
            printError("Error while processing archive spec file: '%s'!" %
                       aaFileName)
            success = BackupStatuses.Failed
            if DEBUG: print traceback.print_exc()
            continue

        # pick right archiver class
        if options.archiver == "tar":
            chosenArchiverClass = archiver.TarArchiver
        elif options.archiver == "targz":
            chosenArchiverClass = archiver.TargzArchiver
        elif options.archiver == "tarbz2":
            chosenArchiverClass = archiver.TarbzArchiver
        elif options.archiver == "tarlzma":
            chosenArchiverClass = archiver.TarlzmaArchiver
        elif options.archiver == "tarxz":
            chosenArchiverClass = archiver.TarxzArchiver

        # create archiver
        chosenArchiver = None
        try:
            chosenArchiver = chosenArchiverClass(spec)

        # >Archiver class raises ValueError if backup level is too high
        except ValueError, ex:
            printError(str(ex))
            success = BackupStatuses.Failed
            if DEBUG: print traceback.print_exc()
            continue

        # execute archive creation
        try:
            chosenArchiver.execute()

        # handle user abort
        except KeyboardInterrupt:
            printError("Aborted by user.")
            sys.exit(2)

        # handle ExecuteException raised by Archiver class
        except archiver.ExecuteException, ex:
            printError(str(ex))
            if ex.errorCode == archiver.ErrorCodes.Warning:
                printError("There were some issues while creating " +
                           "archive '%s'. Check program's " % aaFileName +
                           "output for details.")
                success = BackupStatuses.Issues
            else:
                printError("Creation of the archive for the '%s' failed!" %
                           aaFileName)
                success = BackupStatuses.Failed
            if DEBUG: print traceback.print_exc()

        # catch all other unknown exceptions
        except Exception, ex:
            printError(str(ex))
            printError("Creation of the archive for the '%s' failed!" %
                       aaFileName)
            success = BackupStatuses.Failed
            if DEBUG: print traceback.print_exc()

    # print results
    if options.verbose:
        print
        if success == BackupStatuses.Successful:
            print "Backup completed successfully."
        elif success == BackupStatuses.Issues:
            print "Backup completed successfully with some issues. Check " + \
                "program's output for details."
        else:
            print "Backup operation failed! Check program's output for details."

    # map exit code directly to success value
    sys.exit(success)



# MAIN PROGRAM

main()
