#!/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.
#
"""This job require the Parameterized Build plugin, it's triggered
by http request get method to the job url, for example
http://my.host.com/job/JOB_NAME/buildWithParameters with data
"""

import sys
import os

from common.buildtrigger import trigger_next, trigger_info
from common.buildservice import BuildService
from common.backenddb import BackendDB
from common.snapshot import snapshot_project_enabled
from common.prerelease import is_prerelease_project
def isReadyForPrerelease(build, project):

    return True

def isReadyForCreateSnapshot(build, backenddb, project):

    # whether project is not enabled
    if not snapshot_project_enabled(backenddb, project):
        print "Skipping creating snapshot, project isn't found in repo.yaml"
        return False

    return True

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

    project =  obs_event_fields.get('project') or obs_event_fields.get('sourceproject', '')
    event_type = os.getenv('event_type') 
    if(event_type == 'OBS_REPO_PUBLISHED'):
        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)
        # Init backend database
        redis_host = os.getenv("REDIS_HOST")
        redis_port = int(os.getenv("REDIS_PORT"))
        backenddb = BackendDB(redis_host, redis_port)
        if(is_prerelease_project(project)):
            if(isReadyForPrerelease(build, project)):
                print 'All the repositories are published for project %s.' \
                      'Triggering the prerelease.' % (project)
                trigger_next('#PRERELEASE#%s#%s' %(project,event_type),obs_event_fields)
        else:
            if(isReadyForCreateSnapshot(build, backenddb, project)):
                print 'All the repositories are published for project %s.' \
                      'Triggering the creating snapshot job..'%(project)
                trigger_next('#SNAP#%s#%s' %(project,event_type),obs_event_fields)
    else:
        trigger_next('#%s#%s' %(project,obs_event_fields['event_type']),
                     obs_event_fields)

if __name__ == '__main__':
    # Jenkins task dispatcher, receive events from OBS jenkins notify plugin
    # and create files to trigger downstream jobs
    if len(sys.argv) != 1:
        raise SystemExit('This job do NOT support to carry parameters')

    sys.exit(main(trigger_info(os.getenv('para'))))
