import os import shutil from hashlib import sha1 REMOTE_PATH=os.getenv("REMOTE_PATH", "/mnt/files/nginx") LOCAL_PATH=os.getenv("LOCAL_PATH", "/etc/nginx") ENV={} def refresh_env(): global ENV lines = [l.strip() for l in open('/etc/default/nman')] ENV = {k: v for k, v in [l.split('=') for l in lines]} def apply_env(data): for k, v in ENV.items(): data = data.replace(f'$({k})', v) return data def restart(): return os.system('systemctl restart nginx') == 0 def full_copy(): shutil.rmtree(LOCAL_PATH) os.mkdir(LOCAL_PATH) shutil.copytree(REMOTE_PATH, LOCAL_PATH) def tree(path): if not os.path.exists(path): raise FileNotFoundError() for root, dirs, files in os.walk(path): rl = len(path) pre = root[rl:] if pre.startswith('/'): pre = pre[1:] print(pre) for file in files: yield (0, os.path.join(pre, file)) for dir in dirs: yield (1, os.path.join(pre, dir)) def compare(all=False): refresh_env() remote_tree = [i for i in tree(REMOTE_PATH)] local_tree = [i for i in tree(LOCAL_PATH)] remote_new = [i for i in remote_tree if not i in local_tree] local_new = [i for i in local_tree if not i in remote_tree] outdated = [] for i in [i[1] for i in local_tree if i in remote_tree and i[0] == 0]: data = open(os.path.join(LOCAL_PATH, i), 'r').read() data = apply_env(data).encode() local_hash = sha1(data).digest() data = open(os.path.join(REMOTE_PATH, i), 'r').read() data = apply_env(data).encode() remote_hash = sha1(data).digest() if all or local_hash != remote_hash: outdated += [(0, i)] return {'create': remote_new, 'delete': local_new, 'sync': outdated} def update(force=False): diff = compare(all=force) changes = len([i for i in [diff[k] for k in diff.keys()]]) print(diff) print('changes: %d' % changes) for t, i in diff['create'] + diff['sync']: if t == 1: continue local = os.path.join(LOCAL_PATH, i) remote = os.path.join(REMOTE_PATH, i) print('syncing %s to %s' % (remote, local)) os.makedirs(os.path.dirname(local), exist_ok=True) if local.endswith('.conf'): f = open(local, 'w') f.write(apply_env(open(remote, 'r').read())) f.close() else: shutil.copy(remote, local) for t, i in diff['delete']: path = os.path.join(LOCAL_PATH, i) print('deleting %s' % path) if t == 0: os.unlink(path) else: shutil.rmtree(path) if changes > 0: if not restart(): print("error restartyi ng!") print('done update')