#!/usr/bin/env python

""" this script starts a program and parses its output
    and only returns an output if an error in the
    program has occured.(= no regex matched)

    In this example it filters the output of ftplicity,
    an frontend for duplicity
    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
            ]

# 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

#/hades/shares/software/commercial/bitdefender/update_script.sh update71 de_profadd_80 xcommadd_80 bdssadd_80 bdlmadd_80
# 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()

