#!/usr/bin/python
# vim: set fileencoding=utf-8 : sts=4 : et : sw=4
#    This is a component of mailpie, a full-text search for email
#
#    Copyright © 2008 Jeff Epler <jepler@unpythonic.net>
#    This program 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.
#
#    This program 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 this program; if not, write to the Free Software
#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
"""mailpie-flog: Execute a program and filter out 'progress' lines if output is
not a terminal or the environment variable ALWAYS_FLOG is non-empty"""
import os, sys

if len(sys.argv) < 2 or sys.argv[1] in ("-?", "-h", "--help"):
    print __doc__
    raise SystemExit, 0

if os.isatty(2) and not os.environ.get("ALWAYS_FLOG"):
    os.execvp(sys.argv[1], sys.argv[1:])

import subprocess
import mailpie.log

p = subprocess.Popen(sys.argv[1:], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

s = []
while 1:
    c = p.stdout.read(1)
    #print repr(c), s
    if c == "": break
    if c == "\r":
        del s[:]
    elif c == "\n":
        print "".join(s)
        del s[:]
    else:
        s.append(c)

raise SystemExit, p.wait()
