# 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
# he 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.
#
# Authors: Petr Hracek <*****@*****.**>
#          Tomas Hozza <*****@*****.**>


# It requires fedmsg package
from __future__ import print_function
import fedmsg
from rebasehelper.upstream_monitoring import UpstreamMonitoring

# Testing command line
# echo "{'package':'wget', 'version': '1.6.13'} | fedmsg-logger

for name, endpoint, topic, msg in fedmsg.tail_messages():
    if msg['username'] == 'phracek':
        up = UpstreamMonitoring(name, endpoint, topic, msg)
        up.process_messsage()
    print ('Like rebase-helper-fedmsg <package> <version>')
    sys.exit(1)

package = sys.argv[1]
version = sys.argv[2]

tmp = tempfile.mkdtemp(prefix='thn-', dir='/tmp')
rh_stuff = {}
url = 'http://pkgs.fedoraproject.org/cgit/{package}.git'.format(package=package)
try:
    import sh
    sh.git.clone(url, tmp)
except ImportError:
    pass

rh_upstream = UpstreamMonitoring()
rh_upstream.add_upstream_log_file()
rh_upstream.add_thn_info(tmp, package, version)
ret_code, rh_stuff = rh_upstream.process_thn()
if int(ret_code) == 0:
    print ('Rebase package %s to %s was SUCCESSFUL.' % (package, version))
else:
    ret_code = 1
    print ('Rebase package %s to %s FAILED. See for details.' % (package, version))

print ('Koji scratch build is available here: %s' % rh_stuff['build_log'][int(ret_code)])
print ('Information about patches:\n%s' % '\n'.join(rh_stuff['patches']))
print ('Available log files generated by rebase-helper are:\n%s' % '\n'.join(rh_stuff['logs']))
print ('Checkers %s' % rh_stuff['checkers'])
shutil.rmtree(tmp)