1import os
2import glob
3
4"""
5One day, when this module grows up, it might actually try to fix things.
6'apt-cache search | apt-get install' ... or a less terrifying version of
7the same. With added distro-independant pixie dust.
8"""
9
10def command(cmd):
11    # this could use '/usr/bin/which', I suppose. But this seems simpler
12    for dir in os.environ['PATH'].split(':'):
13        file = os.path.join(os.path.expandvars(os.path.expanduser(dir)), cmd)
14        if os.path.exists(file):
15            return file
16    raise ValueError('Missing command: %s' % cmd)
17
18
19def commands(*cmds):
20    results = []
21    for cmd in cmds:
22        results.append(command(cmd))
23
24
25def library(lib):
26    lddirs = []
27    # read lddirs from  main ld.so.conf file
28    for line in open('/etc/ld.so.conf', 'r').readlines():
29        if line.startswith('include '):
30            glob_pattern = line.split('include ')[1]
31            if not os.path.isabs(glob_pattern):
32                # prepend with a base path of '/etc'
33                glob_pattern = os.path.join('/etc', glob_pattern)
34            glob_result = glob.glob(glob_pattern)
35            for conf_file in glob_result:
36                for conf_file_line in open(conf_file, 'r').readlines():
37                    if os.path.isdir(conf_file_line):
38                        lddirs.append(conf_file_line)
39        else:
40            if os.path.isdir(line):
41                lddirs.append(line.strip())
42
43    lddirs = set(lddirs)
44    lddirs = list(lddirs)
45
46    for dir in ['/lib', '/usr/lib', '/lib64', '/usr/lib64'] + lddirs:
47        file = os.path.join(dir, lib)
48        if os.path.exists(file):
49            return file
50    raise ValueError('Missing library: %s' % lib)
51
52
53def libraries(*libs):
54    results = []
55    for lib in libs:
56        results.append(library(lib))
57
58
59def header(hdr):
60    for dir in ['/usr/include', '/usr/local/include']:
61        file = os.path.join(dir, hdr)
62        if os.path.exists(file):
63            return file
64    raise ValueError('Missing header: %s' % hdr)
65
66
67def headers(*hdrs):
68    results = []
69    for hdr in hdrs:
70        results.append(header(hdr))
71