#! /usr/bin/python

# Copyright (C) 2018 Red Hat, Inc.

# 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.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

"""
Print the log of copr-rpmbuild process to stdout

This script always succeeds (exit status 0), as long as the copr-rpmbuild
process was at all started before.  If the copr-rpmbuild is still running, the
script keeps waiting for the process to end and keeps appending the output to
stdout.
"""

import logging
import os
import sys
import time

WORKDIR = "/var/lib/copr-rpmbuild"
LIVE_LOG = os.path.join(WORKDIR, "main.log")
PIDFILE = os.path.join(WORKDIR, "pid")
MAX_WAIT_FOR_RPMBUILD = 120

def _get_stdout_logger():
    log = logging.getLogger(__name__)
    handler = logging.StreamHandler(sys.stdout)
    handler.setFormatter(logging.Formatter("%(message)s"))
    log.addHandler(log)
    return log

LOG = _get_stdout_logger()

def _tail_log():
    for fname in [PIDFILE, LIVE_LOG]:
        if not os.path.exists(fname):
            LOG.warning("File %s doesn't exist, yet", fname)
            return

    with open(PIDFILE, "r") as pidfd:
        pid = int(pidfd.read().strip())

    tail = "/usr/bin/tail"
    args = [
        tail, "-F", "-n", "+0",
        "--pid={}".format(pid),
        LIVE_LOG,
    ]
    os.execv(tail, args)

def _main():
    start = time.time()
    while True:
        _tail_log()
        if time.time() - start > MAX_WAIT_FOR_RPMBUILD:
            LOG.fatal("Unable to wait for copr-rpmbuild process")
        time.sleep(5)

if __name__ == "__main__":
    _main()
