#!/usr/bin/env python

""" this script starts the ftplicity backup script and parses
    its output and only returns an output if an error by 
    ftplicity has occured.
    Written by Robert Penz <robert@penz.name>
"""

import sys
import os
import re
import popen2

programPath = "/root"
programCommand = "/usr/local/sbin/ftplicity"

regexList = [re.compile(r"Reading globbing filelist .*$"),
             re.compile(r"^--------------\[ Backup Statistics \]--------------$"),
             re.compile(r"^(StartTime|EndTime|ElapsedTime|SourceFiles|SourceFileSize|NewFiles|NewFileSize|DeletedFiles|ChangedFiles|ChangedFileSize|ChangedDeltaSize|DeltaEntries|RawDeltaSize|TotalDestinationSizeChange) .*$"),
             re.compile(r"^Errors 0$"),
	     re.compile(r"^-------------------------------------------------$"),
             re.compile(r"^\s*$"),                           # empty line
	     re.compile(r"Start ftplicity .*$"),
	     re.compile(r"(Using|Test|Cleanup) .*$"),
	     re.compile(r"--- Start running command .*$"),
	     re.compile(r"Skipping .*$"),
	     re.compile(r"--- Finished .*$"),
	     re.compile(r"Running duplicity - OK.*$"),
	     re.compile(r"Output: .*$"),
	     re.compile(r"Last full backup date: .*$")
            ]

# returns true if no error was found in the provided lines
def allLinesOk(lines):
    for line in lines:
        matched = False
        for regex in regexList:
            if regex.match(line):
                matched = True
                break
        if not matched:
            sys.stderr.write("Not matched: %r\n" % line)
            return False
    return True

# Main program: parse command line and start processing
def main():
    os.chdir(programPath)
    child_stdout_and_stderr, child_stdin = popen2.popen4("%s %s" % (programCommand, " ".join(sys.argv[1:])))
    output = child_stdout_and_stderr.readlines()

    if not allLinesOk(output):
        sys.stderr.write("output follows:\n\n")
        for line in output:
            sys.stderr.write(line)


if __name__ == '__main__':
    main()

