#!/usr/bin/python3 import subprocess import sys import os import argparse import json if __name__ == "__main__": parser = argparse.ArgumentParser(description="Backup Dir Size helper") parser.add_argument('PATH') parser.add_argument('--save-new-size', action='store_const', default=False, const=True) args = parser.parse_args() # check parameter # if not args.PATH.replace("/", "").replace("-","").isalnum(): print("Illegal Path: {} (must be alphanum + /)".format(args.PATH)) sys.exit(1) elif not args.PATH.startswith("/"): print("Path mus be absolute ({})".format(args.PATH)) sys.exit(1) elif not os.path.isdir(args.PATH): print("Path does not exist ({}".format(args.PATH)) sys.exit(1) savedir = "/opt/backup-info" savepath = os.path.join(savedir, args.PATH.lstrip("/").replace("/", "-")) currentSize = 0 if os.path.isfile(savepath): with open(savepath) as f: currentSize = int(f.read()) # check # p = subprocess.run(["du", args.PATH], capture_output=True, encoding="utf-8") size = int(p.stdout.split("\n")[-2].split("\t")[0]) if currentSize and currentSize == size: result = { "changed" : False, "old" : currentSize, "new" : size } else: result = { "changed" : True, "old" : currentSize, "new" : size } if args.save_new_size: with open(savepath, "w") as f: f.write(str(size)) # return result print(json.dumps(result))