#!/usr/bin/env python

"""usage: ignis_backup [options]

    -b  backup now
    -c  test if all is ready to backup if we would backup now
        if not send a mail
    -d  use other config file than /etc/ignis.conf
    -h  this help
    -m  don't send mails - pipe all to stdout

ignis is a special backup program for the SOHO sector. It implements a
full-backup strategy based on DVD-RAM (or simular mediums)
(only one medium per run is supported) and a mix between the backup shemes
GFS and Tower of Hanoi.
The normal use is to call the program once a week via cron to backup and once
to check if all is ready and report to the user via mail what is not ready.
"""

import sys
import os
import getopt
import traceback
import tempfile
import shutil

import config_manager
import lock
import backupmethods
import state
import medium
import report
import metadata
import burn

class Backup:
    _configManager = None
    _state = None
    _medium = None
    _report = None
    _metadata = None
    _workingDir = None
    
    def __init__(self, configManager, noMails):
        self._configManager = configManager
        self._noMails = noMails
        self._state = state.State(configManager)
        self._medium = medium.Medium(configManager)
        self._metadata = metadata.Metadata(configManager, self._state.getIdList())
        self._report = report.Report(configManager, noMails)
    
    def _createWorkingDir(self):
        if self._workingDir:
            raise IOError, "Internal Error: workingDir already created !"
        self._workingDir = tempfile.mkdtemp(prefix="ignis-", dir=self._configManager.getTmpDirectory())

    def _removeWorkingDir(self):    
        if not self._workingDir:
            raise IOError, "Internal Error: no workingDir created !"
        shutil.rmtree(self._workingDir)
        self._workingDir = None


    def backup(self):
        """ call this method to do the full progam --> backup the data
        """
                
        stats = []
        errors = []
        traces = []
        volumename = "n/a"
        stateAlreadySet = False
        
        try:
            # check ...
            volumename = self._check()
            
            # we start our transaction
            metadataWorkingDir = self._metadata.begin(volumename)

            #  ... and prepare the medium
            self._medium.init(volumename, check = False)
            
            backupObjects = []
            
            # loop through an backup locations and backup the data
            for location in self._configManager.getBackupLocations().items():
                self._createWorkingDir()
                try:
                    ##FIXME: copying for direct copy is not so good, but we fix later
                    ##       the backup object could return the dir to burn, but the
                    ##       but the problem is the base dir
                    
                    locationDir = os.path.join(self._workingDir, self._configManager.getBackupDirectory(), location[0])
                    os.makedirs(locationDir)
                    
                    # create the right object ...
                    backupObjects.append((location[0],
                                backupmethods.methods[location[1]["method"]](location[0],location[1])))
                    try:
                        #  .... and than call the backup method
                        stats.append(("Backup: " + location[0], backupObjects[-1][1].backup(locationDir)))
                        
                    except Exception, e:
                        stats.append(("Backup: " + location[0], {}))
                        errors.append(("Backup: " + location[0], self._formatError(e)))
                        traces.append(("Backup: " + location[0], traceback.format_exc()))
                
                    # burn the data onto the medium
                    burn.burn(self._configManager.getVolumeDevice(), self._workingDir, volumename, False)
                finally:
                    self._removeWorkingDir()
            
            # loop through an backup locations and verify the data
            # all is burned onto the medium, mount it for a verify
            self._medium.mount()
            basedir = os.path.join(self._configManager.getVolumePath(), self._configManager.getBackupDirectory())
            for location in backupObjects:
                try:
                    #  now call the verify method
                    stats.append(("Verify: " + location[0],
                            location[1].verify(os.path.join(basedir, location[0]), metadataWorkingDir)))
                    
                except Exception, e:
                    stats.append(("Verify: " + location[0], {}))
                    errors.append(("Verify: " + location[0], self._formatError(e)))
                    traces.append(("Verify: " + location[0], traceback.format_exc()))
            self._medium.umount()

            # burn status and other stuff on dvd
            self._state.setBackupEntry(volumename, "Ok", "None")
            stateAlreadySet = True
            self._metadata.commit(self._state.getCurrentID())
        except Exception, e:
            if volumename != "n/a" and not stateAlreadySet:
                try:
                    # only write if we at least could try to write to the medium
                    # and we did not write the state already (which would lead to an too high writeID
                    self._state.setBackupEntry(volumename, "Failed", "Backup was not successfull")
                    self._metadata.commit(self._state.getCurrentID())
                except Exception, e2:
                    errors.append(("global", self._formatError(e2)))
                    traces.append(("global", traceback.format_exc()))

            errors.append(("global", self._formatError(e)))
            traces.append(("global", traceback.format_exc()))
            
        # at last try to unmount the medium and eject it if configured
        try:
            self._medium.eject()
        except Exception, e:
            errors.append(("global", self._formatError(e)))
            traces.append(("global", traceback.format_exc()))

        # send report
        self._report.backupReport(volumename, errors, traces, self._state.getNextBackupID())
    
    
    def check(self):
        """ call this method to only check if a backup would be possible,
            it will report back to you that all is ok or what is not ok
        """
        try:
            self._check()
        except Exception, e:
            # send report only in case of an error
            self._report.checkReport(self._formatError(e), traceback.format_exc())

    def _check(self):
        """ this method performes the action sequence of testing and assuring the
            readiness for a backup, for this it also (u)mounts the medium
            it is called by the check and the backup method, and it throughs an
            exception on any error which needs to be handled by the calling method
            returns the volumename of the medium
        """
        ## currently not implemented
        # to internal checks 
        # check if we can find the data
        # calc size
        
        # all medium stuff is handled in that medium including mounting the medium
        return self._medium.check(self._state.getNextBackupID())
    
    def _formatError(self, e):
        """ returns a string which a human readable error text """
        # args can be empty
        if e.args:
            if len(e.args) > 1:
                return str(e.args)
            else:
                return e.args[0]
        else:
            # print exception class name
            return str(e.__class__)


# Print usage message and exit
def usage(*args):
    sys.stdout = sys.stderr
    print __doc__
    print 50*"-"
    for msg in args: print msg
    sys.exit(2)
    
# Main program: parse command line and start processing
def main():

    if len(sys.argv) == 1:
        usage()

    try:
        opts, args = getopt.getopt(sys.argv[1:], 'bcd:hm')
    except getopt.error, msg:
        usage(msg)

    backupNow = False
    noMails = False
    checkNow = False
    
    configFile = None
    for o, a in opts:
        if o == '-h':
            print __doc__
            sys.exit()
        if o == '-b':
            backupNow = True
        if o == '-c':
            if backupNow:
                usage("The option -c and -b cannot be used at the same time!")
            checkNow = True
        if o == '-d':
            configFile = a
        if o == '-m':
            noMails = True

    myConfigManager = config_manager.ConfigManager(configFile)

    # first lock other instances of me
    if not lock.test_and_lock(myConfigManager.getLockFile()):
        print "An other part of ignis is already running! Aborting"
        sys.exit(2)

    myBackup = Backup(myConfigManager,noMails)
    if checkNow:
        myBackup.check()
    elif backupNow:
        myBackup.backup()
    lock.unlock(myConfigManager.getLockFile())
    
if __name__ == '__main__':
    main()
