#!/usr/bin/python3 # This works around that `mount --bind /foo /bar` is non idempotent. Calling it # 4 times in a row will cause it to be bound over itself 4 times. import argparse import os import pathlib import sys def find_real_mount(): """Look through $PATH to find the first 'mount' that isn't us""" myPath = pathlib.Path(sys.argv[0]).absolute() path = os.get_exec_path() for d in path: mountPath = pathlib.Path(d) / "mount" if not mountPath.exists() or not os.access(mountPath, os.X_OK): continue absPath = mountPath.absolute() if absPath == myPath: continue return absPath def passthrough(args): """Find a system 'mount' command and execute it instead""" mntPath = find_real_mount() args = sys.argv[:] args[0] = str(mntPath) os.execv(args[0], args) def parse_mount_line(line): mountID, parentID, major_minor, source, target, _ = line.split(' ', 5) # print(source, target) return source, target def lookfor_mount_info_target(source, target): """Check if we are already bind mounted at this target""" source = os.path.abspath(source) target = os.path.abspath(target) with open('/proc/self/mountinfo', 'r') as f: for line in f: if target not in line: continue mntsource, mnttarget = parse_mount_line(line) if mnttarget != target: # print(f"not target: {line!r}") continue # this looks to be our target, does the source match? if source.endswith(mntsource): # found us, already there # print(f"target already found: {line!r}") return True # We found a mount target that was exactly us, but it didn't match, keep looking # We made it to the end, and didn't find anything return False def main(): args = sys.argv[1:] if len(args) != 3 or args[0] != '--bind': passthrough(args) return source, target = args[1:] if lookfor_mount_info_target(source, target): print(f"{source} is already bind mounted to {target}") else: passthrough(args) if __name__ == '__main__': main()