import os import shutil import tarfile import time from commia.bearer import get_key, has_key, keys, set_key from commia.prelude import * state_path = Path("state.tar") state_dir = Path("state") def remote_fresh() -> bool: remote_modtime = int(get_key(keys.certificates.state_modtime)) stat = state_path.stat() local_modtime = round(stat.st_mtime) return remote_modtime > local_modtime def pull(): local_exists = state_path.exists() remote_exists = has_key(keys.certificates.state) updated = False if not local_exists and not remote_exists: tarfile.open(state_path, "x").close() updated = True elif remote_exists: if not local_exists or remote_fresh(): print("[*] pulling state") state_path.write_bytes(get_key(keys.certificates.state, decode=False)) updated = True if not updated: return if state_dir.exists(): shutil.rmtree(state_dir) state_dir.mkdir() tar = tarfile.open(state_path, "r") tar.extractall(state_dir, filter="data") def push(): os.remove(state_path) tar = tarfile.open(state_path, "w") for name in os.listdir(state_dir): tar.add(state_dir / name, name, recursive=True) tar.close() state_data = state_path.read_bytes() set_key(keys.certificates.state, state_data) set_key(keys.certificates.state_modtime, str(round(time.time())))