Enforce that the WAR will be deployed and started in the context path,
    while making use of WAR versions in the filename.

    .. note::

        For more info about Tomcats file paths and context naming, please see
        http://tomcat.apache.org/tomcat-7.0-doc/config/context.html#Naming

    name
        The context path to deploy (incl. forward slash) the WAR to.
    war
        Absolute path to WAR file (should be accessible by the user running
        Tomcat) or a path supported by the ``salt.modules.cp.get_url`` function.
    force : False
        Force deployment even if the version strings are the same.
        Disabled by default.
    url : http://localhost:8080/manager
        The URL of the Tomcat Web Application Manager.
    timeout : 180
        Timeout for HTTP requests to the Tomcat Manager.
    temp_war_location : None
        Use another location to temporarily copy the WAR file to.
        By default the system's temp directory is used.
    version : ''
        Specify the WAR version.  If this argument is provided, it overrides
        the version encoded in the WAR file name, if one is present.

        .. versionadded:: 2015.8.6

        Use ``False`` or blank value to prevent guessing the version and keeping it blank.

        .. versionadded:: 2016.11.0

    Example:

    .. code-block:: yaml

        jenkins:
          tomcat.war_deployed:
            - name: /salt-powered-jenkins
            - war: salt://jenkins-1.2.4.war
            - require:
              - service: application-service

    .. note::

        Be aware that in the above example the WAR ``jenkins-1.2.4.war`` will
        be deployed to the context path ``salt-powered-jenkins##1.2.4``. To avoid this
        either specify a version yourself, or set version to ``False``.

def war_deployed(name,
                 war,
                 force=False,
                 url='http://localhost:8080/manager',
                 timeout=180,
                 temp_war_location=None,
                 version=True):
    '''
    Enforce that the WAR will be deployed and started in the context path,
    while making use of WAR versions in the filename.

    .. note::

        For more info about Tomcats file paths and context naming, please see
        http://tomcat.apache.org/tomcat-7.0-doc/config/context.html#Naming

    name
        The context path to deploy (incl. forward slash) the WAR to.
    war
        Absolute path to WAR file (should be accessible by the user running
        Tomcat) or a path supported by the ``salt.modules.cp.get_url`` function.
    force : False
        Force deployment even if the version strings are the same.
        Disabled by default.
    url : http://localhost:8080/manager
        The URL of the Tomcat Web Application Manager.
    timeout : 180
        Timeout for HTTP requests to the Tomcat Manager.
    temp_war_location : None
        Use another location to temporarily copy the WAR file to.
        By default the system's temp directory is used.
    version : ''
        Specify the WAR version.  If this argument is provided, it overrides
        the version encoded in the WAR file name, if one is present.

        .. versionadded:: 2015.8.6

        Use ``False`` or blank value to prevent guessing the version and keeping it blank.

        .. versionadded:: 2016.11.0

    Example:

    .. code-block:: yaml

        jenkins:
          tomcat.war_deployed:
            - name: /salt-powered-jenkins
            - war: salt://jenkins-1.2.4.war
            - require:
              - service: application-service

    .. note::

        Be aware that in the above example the WAR ``jenkins-1.2.4.war`` will
        be deployed to the context path ``salt-powered-jenkins##1.2.4``. To avoid this
        either specify a version yourself, or set version to ``False``.

    '''
    # Prepare
    ret = {'name': name,
           'result': True,
           'changes': {},
           'comment': ''}

    # if version is defined or False, we don't want to overwrite
    if version is True:
        version = __salt__['tomcat.extract_war_version'](war) or ''
    elif not version:
        version = ''

    webapps = __salt__['tomcat.ls'](url, timeout)
    deploy = False
    undeploy = False
    status = True

    # Gathered/specified new WAR version string
    specified_ver = 'version {0}'.format(version) if version else 'no version'

    # Determine what to do
    try:
        # Printed version strings, here to throw exception if no webapps[name]
        current_ver = 'version ' + webapps[name]['version'] \
            if webapps[name]['version'] else 'no version'
        # `endswith` on the supposed string will cause Exception if empty
        if (not webapps[name]['version'].endswith(version)
            or (version == '' and webapps[name]['version'] != version)
            or force):
            deploy = True
            undeploy = True
            ret['changes']['undeploy'] = ('undeployed {0} with {1}'.
                                          format(name, current_ver))
            ret['changes']['deploy'] = ('will deploy {0} with {1}'.
                                        format(name, specified_ver))
        else:
            deploy = False
            ret['comment'] = ('{0} with {1} is already deployed'.
                              format(name, specified_ver))
            if webapps[name]['mode'] != 'running':
                ret['changes']['start'] = 'starting {0}'.format(name)
                status = False
            else:
                return ret
    except Exception:
        deploy = True
        ret['changes']['deploy'] = ('deployed {0} with {1}'.
                                    format(name, specified_ver))

    # Test
    if __opts__['test']:
        ret['result'] = None
        return ret

    # make sure the webapp is up if deployed
    if deploy is False:
        if status is False:
            ret['comment'] = __salt__['tomcat.start'](name, url,
                                                      timeout=timeout)
            ret['result'] = ret['comment'].startswith('OK')
        return ret

    # Undeploy
    if undeploy:
        un = __salt__['tomcat.undeploy'](name, url, timeout=timeout)
        if un.startswith('FAIL'):
            ret['result'] = False
            ret['comment'] = un
            return ret

    # Deploy
    deploy_res = __salt__['tomcat.deploy_war'](war,
                                               name,
                                               'yes',
                                               url,
                                               __env__,
                                               timeout,
                                               temp_war_location=temp_war_location,
                                               version=version)

    # Return
    if deploy_res.startswith('OK'):
        ret['result'] = True
        ret['comment'] = six.text_type(__salt__['tomcat.ls'](url, timeout)[name])
        ret['changes']['deploy'] = ('deployed {0} with {1}'.
                                    format(name, specified_ver))
    else:
        ret['result'] = False
        ret['comment'] = deploy_res
        ret['changes'].pop('deploy')
    return ret