#!/usr/bin/python3.13
#
# Copyright (c) 2015,2018 LAAS/CNRS
# Copyright (c) 2008, Willow Garage, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
#  * Redistributions of source code must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
#  * Redistributions in binary form must reproduce the above
#    copyright notice, this list of conditions and the following
#    disclaimer in the documentation and/or other materials provided
#    with the distribution.
#  * Neither the name of Willow Garage, Inc. nor the names of its
#    contributors may be used to endorse or promote products derived
#    from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
#                                            Anthony Mallet on Mon Nov  9 2015
#

# This file contains a slightly modified copy of functions found in
# roslib.gentools.
# The goal is to avoid using rospack to filter out packages that can be loaded
# or not in get_file_dependencies(). rospack must be avoided because it does
# not work with an empty rosdep cache in ROS_HOME (which is set inside the
# build directory). It is totally unclear why rospack does not work, though.
#
import sys
import os
import os.path
from optparse import OptionParser
from roslib.gentools import compute_md5
import roslib.msgs
import roslib.srvs
import roslib.names
import rospkg

def get_file_dependencies(f):
    """
    Compute dependencies of the specified message/service file
    @param f: message or service file to get dependencies for
    @type  f: str
    @param stdout pipe: stdout pipe
    @type  stdout: file
    @param stderr pipe: stderr pipe
    @type  stderr: file
    @return: 'files': list of files that \a file depends on,
    'deps': list of dependencies by type, 'spec': Msgs/Srvs
    instance.
    @rtype: dict
    """
    package = rospkg.get_package_name(f)
    spec = None
    if f.endswith(roslib.msgs.EXT):
        _, spec = roslib.msgs.load_from_file(f)
    elif f.endswith(roslib.srvs.EXT):
        _, spec = roslib.srvs.load_from_file(f)
    else:
        raise Exception("[%s] does not appear to be a message or service"%spec)
    return get_dependencies(spec, package)

def get_dependencies(spec, package):
    """
    Compute dependencies of the specified Msgs/Srvs
    @param spec: message or service instance
    @type  spec: L{roslib.msgs.MsgSpec}/L{roslib.srvs.SrvSpec}
    @param package: package name
    @type  package: str
    @param stdout: (optional) stdout pipe
    @type  stdout: file
    @param stderr: (optional) stderr pipe
    @type  stderr: file
    @param compute_files: (optional, default=True) compute file
    dependencies of message ('files' key in return value)
    @type  compute_files: bool
    @return: dict:
      * 'files': list of files that \a file depends on
      * 'deps': list of dependencies by type
      * 'spec': Msgs/Srvs instance.
      * 'uniquedeps': list of dependencies with duplicates removed,
      * 'package': package that dependencies were generated relative to.
    @rtype: dict
    """

    deps = []
    if isinstance(spec, roslib.msgs.MsgSpec):
        add_msgs_depends(spec, deps, package)
    elif isinstance(spec, roslib.srvs.SrvSpec):
        add_msgs_depends(spec.request, deps, package)
        add_msgs_depends(spec.response, deps, package)
    else:
        raise MsgSpecException("spec does not appear to be a message or service")

    # convert from type names to file names
    files = {}
    for d in set(deps):
        d_pkg, t = roslib.names.package_resource_name(d)
        d_pkg = d_pkg or package # convert '' -> local package
        files[d] = roslib.msgs.msg_file(d_pkg, t)

    # create unique dependency list
    uniquedeps = []
    for d in deps:
        if not d in uniquedeps:
            uniquedeps.append(d)

    return { 'files': files, 'deps': deps,
             'spec': spec, 'package': package, 'uniquedeps': uniquedeps }

def add_msgs_depends(spec, deps, package_context):
    """
    Add the list of message types that spec depends on to depends.
    @param spec: message to compute dependencies for
    @type  spec: roslib.msgs.MsgSpec/roslib.srvs.SrvSpec
    @param deps [str]: list of dependencies. This list will be updated
    with the dependencies of spec when the method completes
    @type  deps: [str]
    """

    for t in spec.types:
        t = roslib.msgs.base_msg_type(t)
        if not roslib.msgs.is_builtin(t):
            t_package, t_base = roslib.names.package_resource_name(t)

            # special mapping for header
            if t == roslib.msgs.HEADER:
                # have to re-names Header
                deps.append('std_msgs/Header')

            if roslib.msgs.is_registered(t):
                depspec = roslib.msgs.get_registered(t)
                if t != roslib.msgs.HEADER:
                    if '/' in t:
                        deps.append(t)
                    else:
                        deps.append(package_context+'/'+t)
            else:
              key, depspec = roslib.msgs.load_by_type(t, package_context)
              if t != roslib.msgs.HEADER:
                deps.append(key)
                roslib.msgs.register(key, depspec)

            add_msgs_depends(depspec, deps, package_context)

# parse options
p = OptionParser(usage = 'usage: %prog [options] file',
                 prog = os.path.basename(__file__))

p.add_option('-o', action = 'store', dest = 'dest',
             metavar = 'FILE', help = 'Output md5 in FILE')
p.add_option('-f', action = 'store', dest = 'fmt',
             metavar = 'FORMAT', help = 'Printf format for md5')
p.add_option('-M', action = 'store_true', dest = 'deps',
             help = 'Generate dependency file')
p.add_option('--Mf', action = 'store', dest = 'depfmt',
             metavar = 'FORMAT', help = 'Printf format for deps')
p.add_option('--dcat', action = 'store', dest = 'dcat', metavar = 'FORMAT',
             help = 'Generate concatenated dependency messages')

(options, args) = p.parse_args()

if len(args) != 1:
  p.error("no input file")

# we're going to manipulate internal apis of msgs, so have to manually init
roslib.msgs._init()

# rospack instance for caching deps
rospack = rospkg.RosPack()

# get dependencies
try:
  deps = get_file_dependencies(args[0])
except Exception as e:
  print('%s: %s' % (args[0], str(e)))
  sys.exit(2)

# create dependency file
if options.deps:
  if options.dest:
    if not options.depfmt:
      options.depfmt = options.dest
    with open(options.dest + '.d', "w") as d:
      for f in deps['files'].values():
        d.write('%s: %s\n' % (options.depfmt, f))
    os.utime(options.dest + '.d', None) # force mtime
  else:
    p.error('-M requires -o')

# create dcat data
if options.dcat:
  with open(args[0], 'r') as f:
    dcat = f.read()
  for d in deps['files']:
    dcat += '\n' + '='*80 + '\n'
    dcat += 'MSG: %s\n' % d
    with open(deps['files'][d], 'r') as f:
      dcat += f.read()
  dcat = dcat.replace('\n', '\\n\\\n')
  dcat = dcat.replace('"', '\\"')

# compute md5
md5 = compute_md5(deps, rospack=rospack)
if not options.fmt:
  options.fmt = '%s'

if options.dest:
  with open(options.dest, "w") as d:
    d.write((options.fmt + '\n') % md5)
    if options.dcat:
      d.write((options.dcat + '\n') % dcat)
else:
  print(options.fmt % md5)
  if options.dcat:
    print((options.dcat + '\n') % dcat)
