🗝
summary refs log tree commit diff
path: root/lib.py
diff options
context:
space:
mode:
authormia <mia@mia.jetzt>2024-06-08 22:56:14 -0700
committermia <mia@mia.jetzt>2024-06-08 22:56:14 -0700
commit5016065f2c1b959e578bc18cfcab226db970b401 (patch)
tree28b0826702f391651ebbf65d15ff06cf3f2227f5 /lib.py
downloadcertificates-5016065f2c1b959e578bc18cfcab226db970b401.tar.gz
certificates-5016065f2c1b959e578bc18cfcab226db970b401.zip
initial commit
Diffstat (limited to 'lib.py')
-rw-r--r--lib.py49
1 files changed, 49 insertions, 0 deletions
diff --git a/lib.py b/lib.py
new file mode 100644
index 0000000..3aee069
--- /dev/null
+++ b/lib.py
@@ -0,0 +1,49 @@
+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())))