#!/usr/bin/env python3
# -*- coding: utf-8 -*-

# ==============================================================================
# Copyright and license info is available in the LICENSE file included with
# the Server Deployment Package (SDP), and also available online:
# https://swarm.workshop.perforce.com/projects/perforce-software-sdp/view/main/LICENSE
# ------------------------------------------------------------------------------

# tag::includeManual[]
"""
NAME:
    CheckFixes.py

DESCRIPTION:
    This trigger is intended for use with P4DTG (Defect Tracking Replication) installations.

    It will allows fixes to be added or deleted depending on the values of job fields.
    Thus you can control workflow and disallow fixes if jobs are in a particular state.
    So if the field JiraStatus is closed, then you are not allowed to add or delete a fix.

    To install, add a line to your Perforce triggers table like the following:

        check-fixes fix-add //... "python /p4/common/bin/triggers/CheckFixes.py -p %serverport% -u perforce %change% %client% %jobs%"
        check-fixes fix-delete //... "python /p4/common/bin/triggers/CheckFixes.py -p %serverport% -u perforce --delete %change% %client% %jobs%"

    or (if server is standard SDP and has appropriate environment defaults for P4PORT and P4USER):

        check-fixes fix-add //... "python /p4/common/bin/triggers/CheckFixes.py %change% %client% %jobs%"
        check-fixes fix-delete //... "python /p4/common/bin/triggers/CheckFixes.py --delete %change% %client% %jobs%"

    You may need to provide the full path to python executable, or edit the path to the trigger.

    Also, don't forget to make the file executable.
"""
# end::includeManual[]

# Python 2.7/3.3 compatibility.
from __future__ import print_function

import sys
import P4
import WorkflowTriggers
from os.path import basename, splitext

trigger_name = basename(splitext(__file__)[0])

class CheckFixes(WorkflowTriggers.WorkflowTrigger):
    """See module doc string for details"""

    def __init__(self, *args, **kwargs):
        WorkflowTriggers.WorkflowTrigger.__init__(self, **kwargs)
        self.parse_args(__doc__, args)

    def add_parse_args(self, parser):
        """Specific args for this trigger - also calls super class to add common trigger args"""
        parser.add_argument('-c', '--config-file', default=None,
                            help="Configuration file for trigger. Default: CheckFixes.yaml")
        parser.add_argument('-d', '--delete', default=False, action="store_true",
                            help="Whether this is Fix-Delete trigger. Default: False so Fix-Add assumed")
        parser.add_argument('change', help="Change to validate - %%change%% argument from triggers entry.")
        parser.add_argument('workspace', help="Workspace within which change is being made - %%client%% argument from triggers entry.")
        parser.add_argument('jobs', nargs='+',
                            help="List of jobs - %%jobs%% argument from triggers entry.")
        super(CheckFixes, self).add_parse_args(parser)

    def map_includes_all_files(self, files, paths):
        """Returns True if the change list files are all included in specified paths"""
        map = P4.Map()
        for p in paths:
            map.insert(p)
        for df in files:
            if not map.includes(df):
                return False
        return True

    def run(self):
        """Runs trigger"""
        try:
            self.logger.debug("%s firing" % trigger_name)
            config = self.load_config(self.options.config_file)
            errors = []
            for k in "fix_state_field fix_allowed_states msg_cant_link_jobs".split():
                if k not in config:
                    errors.append("Config file %s missing definition for %s" %
                                  (self.options.config_file, k))
            if errors:
                msg = "%s: Invalid config file for trigger %s\n" % (trigger_name, str(errors))
                self.message(msg)
                return 1

            self.setupP4()
            self.p4.connect()

            if self.options.change == 'default':
                files = [x['depotFile'] for x in self.p4.run_opened("-C", self.options.workspace, "-c", "default")]
            else:
                change = self.getChange(self.options.change)
                # Allow fixes to be deleted from pending changelists
                if change.status == 'pending' and self.options.delete:
                    self.logger.debug("%s: Allowing fix delete for pending change" % trigger_name)
                    return 0
                files = [x.depotFile for x in change.files]

            # If we match the fix allowed paths then don't check further
            prj = self.get_project_by_files(config, files)
            self.logger.debug("prj: %s" % str(prj))
            if not prj:
                self.logger.debug("%s: Allowing fix action as no project affected" % trigger_name)
                return 0

            if 'fix_allowed_paths' in prj and prj['fix_allowed_paths']:
                if self.map_includes_all_files(files, prj['fix_allowed_paths']):
                    self.logger.debug("%s: Allowing fix action as per fix_allowed_paths" % trigger_name)
                    return 0

            jobs = []
            for jobname in self.options.jobs:
                jobs.append(self.p4.fetch_job(jobname))

            errors = []
            for job in jobs:
                if config['fix_state_field'] in job and \
                                job[config['fix_state_field']] not in config['fix_allowed_states']:
                    errors.append("Job %s has state '%s'" %
                                  (job['Job'], job[config['fix_state_field']]))

            if errors:
                err_msg = "\n".join(config['msg_cant_link_jobs'])
                states = ["'%s'" % s for s in config['fix_allowed_states']]
                msg = err_msg + "\nAllowed states: %s\n" % ", ".join(states) +\
                      "\n".join(errors) + "\n\n"
                self.message(msg)
                return 1
        except Exception:
            return self.reportException()

        return 0


if __name__ == '__main__':
    """ Main Program"""
    trigger = CheckFixes(*sys.argv[1:])
    sys.exit(trigger.run())
