#!/usr/bin/env python

"""usage: ignis_recovery [options] command [paramters]

    Following commands are currently supported:
    
    list
            lists all files and their versions on all mediums in a
            form which is easy parseable by a script - this
            command is not indented for normal users
    search <substring>
            search for the provided substring in the full
            pathes of the files and list the matches
    show <fullpath>
            shows which version of the provided full path
            is on what medium. the result is grouped by
            the version
    restore <fullpath>
            restores the file or directory (with all its content)
            from the inserted medium relative to the currently
            directory
    
    -d  use other config file than /etc/ignis.conf
    -h  this help

ignis_recovery is the program for ignis to restore, search, list and
show the history of previously backuped files. You only need it,
if you want a confortable way, as all file are stored in a standard
way on the mediums - so you can use standard unix tools for it too.
"""

import sys
import os
import getopt
import time

import config_manager
import lock
import backupmethods
import state
#import medium
import metadata

# remove the special handle ones from the list
bulkMetaData = [x for x in backupmethods.backupmethodbase.metadataStructureList if not x in ["mtime", "name", "type"]]

class Recovery:
    _configManager = None
    _state = None
    #_medium = None
    _metadata = None
    
    def __init__(self, configManager):
        self._configManager = configManager
        self._state = state.State(configManager)
        #self._medium = medium.Medium(configManager)
        self._metadata = metadata.Metadata(configManager, self._state.getIdList())

    def list(self):
        """ lists all files and their versions on all mediums in a
            form which is easy parseable by a script - this
            command is not indented for normal users
        """
        print self._metadata.getMetaDataDict()
        
    def search(self, s):
        """ lists all files which contain the search string """
        iMetadata = self._metadata.getMetaDataDict().iteritems()
        while True:
            try:
                entry = iMetadata.next()
            except StopIteration: break
            if entry[0].find(s) > -1:
                print entry[0]
    
    def show(self, s):
        """ shows which version of the provided full path
            is on what medium. the result is grouped by
            the version
        """
        iMetadata = self._metadata.getMetaDataDict().iteritems()
        while True:
            try:
                entry = iMetadata.next()
            except StopIteration: break
            if entry[0] == s:
                self._printEntry(entry)
    
    
    def _printEntry(self, entry):
        """ prints the history of the provided file/directory """
        def sortByMtime(aDict):
            """ sort the given dict by the mtime and return a list """
            A = [ (- int(s[1]["mtime"]), s) for s in aDict.items()]
            A.sort()
            return [t[1] for t in A]

        def printMetaData(ids, metadata):
            """ prints the meta date for a set of ids which has the same metadata """
            
            # nothing to print
            if not ids:
                return 
            
            print "  IDs: %s" % ", ".join(ids)
            print "    type      : %s" % backupmethods.backupmethodbase.typeList[metadata["type"]]
            print "    mtime     : %s" % time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(int(metadata["mtime"])))
            for entry in bulkMetaData:
                try:
                    print "    %-10s: %s" % (entry, metadata[entry])
                except LookupError:
                    pass
            
        print "%s:" % entry[0]
        lastMetadata = {}
        unchangedIDs = []
        for aId in sortByMtime(entry[1]):
            changedEntries = [y for y in aId[1].items() if y[1] != lastMetadata.get(y[0], None)]
            if changedEntries:
                printMetaData(unchangedIDs, lastMetadata)
                lastMetadata = aId[1]
                unchangedIDs = [aId[0]]
            else:
                unchangedIDs.append(aId[0])
        
        printMetaData(unchangedIDs, lastMetadata)


# 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("No options, commands, paramters provided!")
    try:
        opts, args = getopt.getopt(sys.argv[1:], 'd:h')
    except getopt.error, msg:
        usage(msg)
    
    # first check the options now the rest
    configFile = None
    for o, a in opts:
        if o == '-h':
            print __doc__
            sys.exit()
        if o == '-d':
            configFile = a
            
    if not args:
        usage("No command provided!")
    elif not args[0] in ["list", "search", "show", "restore"]:
        usage("No valid command provided!")
    else:
        command = args[0]
    
    if args[0] in ["list"]:
        if len(args) != 1:
            usage("This command has no paramters!")
    elif args[0] in ["search", "show", "restore"]:
        if len(args) != 2:
            usage("This command needs exactly ONE paramter!")
        paramter = args[1]
        
    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)

    myRecovery = Recovery(myConfigManager)
    
    if command == "list":
        myRecovery.list()
    elif command == "search":
        myRecovery.search(paramter)
    elif command == "show":
        myRecovery.show(paramter)
    elif command == "restore":
        print "This function is currently not implemented - read the READ on how to restore from a backup"
            
    lock.unlock(myConfigManager.getLockFile())
    
if __name__ == '__main__':
    main()
