import os
import subprocess
roots = ["/etc", "/run", "/usr/local", "/usr/lib", "/lib"]
def gather_files(name, suffix):
pathname_by_basename = {}
for r in roots:
dirname = os.path.join(r, name)
if os.path.isdir(dirname):
for basename in os.listdir(dirname):
if basename.endswith(suffix) and basename not in pathname_by_basename:
pathname_by_basename[basename] = os.path.join(dirname, basename)
sorted_basenames = sorted(pathname_by_basename.keys())
return [pathname_by_basename[basename] for basename in sorted_basenames]
def unit_exists(unit):
load_state = subprocess.check_output(["systemctl", "show", "--value", "-p", "LoadState", unit],
universal_newlines=True).strip()
return load_state != "not-found" and load_state != "masked"
def first_unit(files):
for f in files:
with open(f) as c:
for ll in c.readlines():
w = ll.strip()
if w != "" and not w.startswith("#") and unit_exists(w):
return w
return None
unit = first_unit(gather_files("systemd/ntp-units.d", ".list"))
if unit:
print(unit)