#!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4
#
# Copyright (C) 2016 Samsung
#
#    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 repa webpage
"""

import os
import re
import sys
import shutil

from xml.dom import minidom
import xml.etree.ElementTree as ElementTree

from gbp.git.repository import GitRepositoryError

from osc import core

from common.gerrit import Gerrit, get_gerrit_event, GerritError, is_ref_deleted
from common.git import Git, clone_gitproject
from common.buildservice import BuildService
from common.prerelease import get_prerelease_project_name
from common.buildtrigger import trigger_info, trigger_next
from common import runner

class LocalError(Exception):
    """Local error exception."""
    pass

#-------------------------------------------------------------------------------
# global variables
status_str = ""
error_string = ""
obs_api = os.getenv("OBS_API_URL")
obs_user = os.getenv("OBS_API_USERNAME")
obs_passwd = os.getenv("OBS_API_PASSWD")

repa_decision = os.getenv("REPA_DECISION")
obs_project = os.getenv("OBS_PROJECT")
sr_tag = os.getenv("SR_TAG")
repa_comment = os.getenv("REPA_COMMENT")
repa_user = os.getenv("REPA_USER")

#-------------------------------------------------------------------------------
def is_aggregate_package(build, proj, pack):
    if "_aggregate" in build.get_src_file_list(proj, pack):
        return True

    return False

def is_link_package(build, proj, pack):
    if "_link" in build.get_src_file_list(proj, pack):
        return True

    return False

def check_permission(build, project, userid):
    meta_xml = build.get_meta(project)
    print meta_xml
    xml_root = ElementTree.fromstringlist(meta_xml)
    for person in xml_root.findall('person'):
        if person.attrib['role'] == 'maintainer' and userid == person.attrib['userid']:
            return True

    return False


def accept_or_reject(build, prerelease_proj, git_tag, state, comment=''):
    info = build.get_info(prerelease_proj)

    print "repa %s %s (%s)" % (state, git_tag, prerelease_proj)
    global status_str
    status_str = state

    submitter = info['submitter']
    projects = '[' + ', '.join(info['projects']) + ']'
    message = ''
    if submitter:
        message = "Submitter: %s\n" % submitter

    message += "Comments: %s \nGit project: %s\nTag: %s" \
        % (comment or "submission %s" % str(git_tag),
           projects, git_tag)

    target_prj = str(info['obs_target_prj'])

    # Create SR
    org_source_packages=build.get_package_list(prerelease_proj)
    source_packages=[]
    for p in org_source_packages:
        if not is_aggregate_package(build, prerelease_proj, p):
            source_packages.append(p)

    reqid = build.create_sr(prerelease_proj, source_packages,
                          target_prj, message=message)

    print 'created SR %s' % reqid

    # and immediately set its state
    message = "SR %s is set to %s" % (reqid, state)
    if comment:
        message += comment
    build.set_sr_state(reqid, state=state,
                 message=str(message), force=True)
    print 'set SR state to', state

def repa_reject(build, proj, git_tag, comment=''):
    accept_or_reject(build, proj, git_tag, 'declined', comment)

def repa_accept(build, proj, git_tag, comment=''):
    accept_or_reject(build, proj, git_tag, 'accepted', comment)

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

    print '---[JOB STARTED: repa]-------------------------'

    print "OBS_PROJECT = ", obs_project
    print "SR_TAG = ", sr_tag
    print "REPA_COMMENT = ", repa_comment
    print "REPA_DECISION = ", repa_decision
    print "REPA_USER = ", repa_user

    build = BuildService(obs_api, obs_user, obs_passwd)
    ret = 0

    # home:prerelease:Tizen:Mobile:submit:tizen:20161025.103628
    prerelease_proj=get_prerelease_project_name(obs_project, sr_tag)

    if os.getenv("REPA_CHECK_PERMISSION", 0):
        if not check_permission(build, obs_project, repa_user):
            raise LocalError("User %s does not have permission for OBS project %s" % (repa_user, obs_project))

    if repa_decision == "accept":
        repa_accept(build, prerelease_proj, sr_tag, repa_comment)
    else:
        repa_reject(build, prerelease_proj, sr_tag, repa_comment)

    return 0

if __name__ == '__main__':
    try:
        exit_status = main()
    except Exception as err:
        print err
        global status_str, error_string
        status_str = "Failed"
        error_string = str(err)
        exit_status = 1

bm_stage = "REPA"

bm_data = {"bm_stage": bm_stage,
           "sr_tag": sr_tag,
           "profile":obs_project,
           "status": status_str,
           "status_reason": error_string}
trigger_next("BUILD-MONITOR", bm_data)

sys.exit(exit_status)
