#!/usr/bin/python
# -*- coding: utf-8 -*-
#    Copyright (C) 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.const import *
from fwbackups.i18n import _
from fwbackups import backend, utils, config, fwlogger

def usage(e=None):
    if e:
        print _('Invalid usage: %s'  % e)
    print _('Usage: fwbackups-runonce [OPTIONS] Path(s) Destination\n\
  Options:\n\
    -v, --verbose  :  Increase verbosity (print debug messages)\n\
    -h, --help  :  Print this message and exit\n\
    -r, --recursive  :  Perform a recursive backup\n\
    -i, --hidden  :  Include hidden files in the backup\n\
    -p, --packages2file  :  Print installed package list to a text file\n\
    -d, --diskinfo2file  :  Print disk geometry to a file (must be root)\n\
    -s, --sparse  :  Handle sparse files efficiently\n\
    -e, --engine=ENGINE  :  Use specified backup engine.\n\
                            Valid engines are tar, tar.gz and rsync.\n\
    -x, --exclude=\'PATTERNS\'  :  A double-space separated sequence patterns.\n\
                                 If a file matches any of the patterns, skip it.\n\
                                 Remember to wrap the list in \'single quotes\'.\n\
    -n, --nice=NICE  :  Indicate the niceness of the backup process (-20 to 19)\n\
\n\
  Path(s) is space-seperated list of paths to include in the backup.\n\
  Destination is the directory where the OneTime backup should be placed within.\n\
\n\
  Defaults to tar engine, and no other options unless specified otherwise.\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)
    logger.setLevel(logging.INFO)
    onetime = config.OneTimeConf(True)
    onetime.set('Options', 'Recursive', 0)
    onetime.set('Options', 'Hidden', 0)
    onetime.set('Options', 'PkgListsToFile', 0)
    onetime.set('Options', 'DiskInfoToFile', 0)
    onetime.set('Options', 'Sparse', 0)
    verbose = False
    paths = []
    try:
        avalableOptions = ["help", "verbose", "recursive", "hidden",\
                           "packages2file", "diskinfo2file", "sparse",\
                           "engine", "exclude", "nice"]
        # letter = plain options
        # letter: = option with arg
        (opts, rest_args) = getopt.gnu_getopt(sys.argv[1:],"hvripdse:x:n:", avalableOptions)
    except (getopt.GetoptError), e:
        print e, ""
        usage()
        sys.exit(1)
    # Remove options from paths
    paths = sys.argv[1:]
    for i in opts:
        for ii in i:
            try:
                paths.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":
                logger.setLevel(logging.DEBUG)
            if opt == "-r" or opt == "--recursive":
                onetime.set('Options', 'Recursive', 1)
            if opt == "-i" or opt == "--hidden":
                onetime.set('Options', 'Hidden', 1)
            if opt == "-p" or opt == "--packages2file":
                onetime.set('Options', 'PkgListsToFile', 1)
            if opt == "-d" or opt == "--diskinfo2file":
                onetime.set('Options', 'DiskInfoToFile', 1)
            if opt == "-s" or opt == "--sparse":
                onetime.set('Options', 'Sparse', 1)
            if opt == "-e" or opt == "--engine":
                if value == 'tar' or value == 'tar.gz' or value == 'rsync':
                    onetime.set('Options', 'engine', value)
                else:
                    usage()
                    sys.exit(1)
            if opt == "-x" or opt == "--exclude":
                onetime.set('Options', 'Excludes', value)
            if opt == "-n" or opt == "--nice":
                if int(value) >= -20 and int(value) <= 19:
                    if UID != 0 and int(value) < 0:
                        usage(_('You must be root to set a niceness below 0'))
                        sys.exit(1)
                    onetime.set('Options', 'Nice', value)
                else:
                    usage()
                    sys.exit(1)
    # handle ctrl + c
    signal.signal(signal.SIGINT, handleStop)
    if os.path.exists(onetimeloc):
        os.remove(onetimeloc)
    if len(paths) < 2:
        usage(_('Invalid usage: Requires at least one path and a destination'))
        sys.exit(1)
    onetime.set('Options', 'Destination', paths[-1])
    pathnumber = 0
    for i in paths[:-1]:
        pathno = 'path' + str(pathnumber)
        onetime.set('Paths', pathno, i)
        pathnumber = int(pathnumber + 1)
    try:
        backupHandle = backend.OneTime(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)


