#!/usr/bin/env python
#
# Copyright (C) 2010, 2011, 2012, 2013, 2014 Intel, 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; version 2
#    of the License.
#
#    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.
#
"""Publish the test results to OBS"""

import os
import sys
from common.buildservice import BuildService
from common.buildtrigger import trigger_info



def main():
    """The main body"""

    try:
        api_url = os.getenv("OBS_API_URL")
        api_username = os.getenv("OBS_API_USERNAME")
        api_password = os.getenv("OBS_API_PASSWD")
        fields = trigger_info(os.getenv("TRIGGER_INFO"))

        project = fields["project"]
        result = fields["test_result"]
        name = fields["name"]
        test_details = fields["test_details"]


        build = BuildService(api_url, api_username, api_password)
        info = build.get_info(str(project))
        for i in range(len(info["images"])):
            if info["images"][i]["name"] == name:
                info["images"][i]["test_status"] = result
                info["images"][i]["test_details"] = test_details
                break
        build.update_info(info, project)
    except (TypeError) as error:
        sys.exit("Error accessing OBS: " + str(error))


if __name__ == "__main__":
    sys.exit(main())
