#!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4
#
# 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.
#
"""
This code is called by gerrit-plugin to load the backend config to redis.
"""

import os, sys
import re

from common.buildservice import BuildService


def main():
    """Script entry point.
    """

    if not (os.getenv("GERRIT_EVENT_TYPE") == "change-merged" \
        or os.getenv("GERRIT_EVENT_TYPE") == "change-abandoned"):
        print "Invalid event type %s" % os.getenv("GERRIT_EVENT_TYPE")
        return

    refspec = os.getenv("GERRIT_REFSPEC")
    change_number, change_version = re.search(r'refs/changes/[0-9]+/([0-9]+)/([0-9]+)', refspec).groups()
    project = os.path.basename(os.getenv("GERRIT_PROJECT"))
    mode = os.getenv("GERRIT_PROJECT").split('/')[0]

    obs_api = os.getenv("OBS_API_URL")
    obs_user = os.getenv("OBS_API_USERNAME")
    obs_passwd = os.getenv("OBS_API_PASSWD")
    build = BuildService(obs_api, obs_user, obs_passwd)

    for x in range(1, int(change_version) + 1):
        delete_project_name = "home:tester:Tools-%s-%s-%s.%d" \
                  % (mode, project, change_number, x)
        print 'Deleting %s...' % delete_project_name
        build.cleanup(delete_project_name, "Cleaned by purge job")

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

