1#!/usr/bin/env python3 2# SPDX-License-Identifier: CC0-1.0 3 4""" 5 6Proof-of-concept systemd environment generator that makes sure that bin dirs 7are always after matching sbin dirs in the path. 8(Changes /sbin:/bin:/foo/bar to /bin:/sbin:/foo/bar.) 9 10This generator shows how to override the configuration possibly created by 11earlier generators. It would be easier to write in bash, but let's have it 12in Python just to prove that we can, and to serve as a template for more 13interesting generators. 14 15""" 16 17import os 18import pathlib 19 20def rearrange_bin_sbin(path): 21 """Make sure any pair of …/bin, …/sbin directories is in this order 22 23 >>> rearrange_bin_sbin('/bin:/sbin:/usr/sbin:/usr/bin') 24 '/bin:/sbin:/usr/bin:/usr/sbin' 25 """ 26 items = [pathlib.Path(p) for p in path.split(':')] 27 for i in range(len(items)): 28 if 'sbin' in items[i].parts: 29 ind = items[i].parts.index('sbin') 30 bin = pathlib.Path(*items[i].parts[:ind], 'bin', *items[i].parts[ind+1:]) 31 if bin in items[i+1:]: 32 j = i + 1 + items[i+1:].index(bin) 33 items[i], items[j] = items[j], items[i] 34 return ':'.join(p.as_posix() for p in items) 35 36if __name__ == '__main__': 37 path = os.environ['PATH'] # This should be always set. 38 # If it's not, we'll just crash, which is OK too. 39 new = rearrange_bin_sbin(path) 40 if new != path: 41 print('PATH={}'.format(new)) 42