1#!/usr/bin/env python
2# Copyright (c) 2011 The Chromium Authors. All rights reserved.
3# Use of this source code is governed by a BSD-style license that can be
4# found in the LICENSE file.
5
6"""cups-config wrapper.
7
8cups-config, at least on Ubuntu Lucid and Natty, dumps all
9cflags/ldflags/libs when passed the --libs argument.  gyp would like
10to keep these separate: cflags are only needed when compiling files
11that use cups directly, while libs are only needed on the final link
12line.
13
14This can be dramatically simplified or maybe removed (depending on GN
15requirements) when this is fixed:
16  https://bugs.launchpad.net/ubuntu/+source/cupsys/+bug/163704
17is fixed.
18"""
19
20import subprocess
21import sys
22
23def usage():
24  print 'usage: %s {--api-version|--cflags|--ldflags|--libs|--libs-for-gn}' % \
25      sys.argv[0]
26
27
28def run_cups_config(mode):
29  """Run cups-config with all --cflags etc modes, parse out the mode we want,
30  and return those flags as a list."""
31
32  cups = subprocess.Popen(['cups-config', '--cflags', '--ldflags', '--libs'],
33                          stdout=subprocess.PIPE)
34  flags = cups.communicate()[0].strip()
35
36  flags_subset = []
37  for flag in flags.split():
38    flag_mode = None
39    if flag.startswith('-l'):
40      flag_mode = '--libs'
41    elif (flag.startswith('-L') or flag.startswith('-Wl,')):
42      flag_mode = '--ldflags'
43    elif (flag.startswith('-I') or flag.startswith('-D')):
44      flag_mode = '--cflags'
45
46    # Be conservative: for flags where we don't know which mode they
47    # belong in, always include them.
48    if flag_mode is None or flag_mode == mode:
49      flags_subset.append(flag)
50
51  # Note: cross build is confused by the option, and may trigger linker
52  # warning causing build error.
53  if '-lgnutls' in flags_subset:
54    flags_subset.remove('-lgnutls')
55
56  return flags_subset
57
58
59def main():
60  if len(sys.argv) != 2:
61    usage()
62    return 1
63
64  mode = sys.argv[1]
65  if mode == '--api-version':
66    subprocess.call(['cups-config', '--api-version'])
67    return 0
68
69  # All other modes get the flags.
70  if mode not in ('--cflags', '--libs', '--libs-for-gn', '--ldflags'):
71    usage()
72    return 1
73
74  if mode == '--libs-for-gn':
75    gn_libs_output = True
76    mode = '--libs'
77  else:
78    gn_libs_output = False
79
80  flags = run_cups_config(mode)
81
82  if gn_libs_output:
83    # Strip "-l" from beginning of libs, quote, and surround in [ ].
84    print '['
85    for lib in flags:
86      if lib[:2] == "-l":
87        print '"%s", ' % lib[2:]
88    print ']'
89  else:
90    print ' '.join(flags)
91
92  return 0
93
94
95if __name__ == '__main__':
96  sys.exit(main())
97