#!/usr/bin/python
# -*- coding: utf-8 -*-
#    Copyright (C) 2005, 2006, 2007 Stewart Adam
#    This file is part of fwbackups.

#    fwbackups 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.

#    fwbackups 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 fwbackups; if not, write to the Free Software
#    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
import os
import sys
import time
import signal
import getopt
import logging
from fwbackups.i18n import _
from fwbackups import backend, utils, fwlogger

def usage(e):
    if e:
        print _('Invalid usage: %s'  % e)
    print _('Usage: fwbackups-run [OPTIONS] Set_Name(s)\n\
  Options:\n\
    -v, --verbose  :  Increase verbosity (print debug messages)\n\
    -h, --help  :  Print this message and exit\n\
    -l, --silent  :  Print messages to log file only\n\
\n\
  Set_Name(s) is space-seperated list of set names to run backups of.\n\
')

def handleStop(arg1, arg2):
    """ Handles a siging """
    backupHandle.cancel()

# Only if we're in main execution
if __name__ == "__main__":
    logger, handler = fwlogger._setupLogger(False, True)
    verbose = False
    try:
        avalableOptions = ["help", "verbose", "silent"]
        # letter = plain options
        # letter: = option with arg
        (opts, rest_args) = getopt.gnu_getopt(sys.argv[1:],"hvl", avalableOptions)
    except (getopt.GetoptError), e:
        print e, ""
        usage()
        sys.exit(1)
    # Remove options from paths
    sets = sys.argv[1:]
    for i in opts:
        for ii in i:
            try:
                sets.remove(ii)
            except:
                pass
    # Parse args, take action
    if opts == []:
        pass
    else:
        for (opt, value) in opts:
            if opt == "-h" or opt == "--help":
                usage()
                sys.exit(1)
            if opt == "-v" or opt == "--verbose":
                verbose = True
            if opt == "-l" or opt == "silent":
                logger.setPrintToo(False)
    # handle ctrl + c
    signal.signal(signal.SIGINT, handleStop)
    if not len(sets) >= 1:
        usage(_('Invalid usage: Requires at least one set name to backup'))
        sys.exit(1)
    else:
        if verbose == True:
            logger.setLevel(logging.DEBUG)
        else:
            logger.setLevel(logging.INFO)
        for i in sets:
            try:
                backupHandle = backend.Automated(i, logger=logger)
                backupThread = utils.FuncAsThread(backupHandle.backup)
            except Exception, e:
                print _('ERROR: Cannot setup threading. Exiting.')
                print _('Error was: %s' % str(e))
                sys.exit(1)
            backupThread.start()
            while backupThread.isAlive():
                time.sleep(0.02)
        
