File size: 9,894 Bytes
0479352
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
#!/usr/bin/env python3
"""
Antigravity Manager β€” Supabase Sync + App Launcher
===================================================
This single file handles everything:
  1. Downloads backup from Supabase on startup (if exists)
  2. Starts the Antigravity Manager app
  3. Watches for changes every 60s and backs up to Supabase
  4. On shutdown, does a final backup

SETUP: Either edit the keys below OR set them as HF Space secrets.
       HF secrets (env vars) override the values below.
"""

import os
import sys
import time
import signal
import hashlib
import tarfile
import tempfile
import logging
import subprocess
import threading

# ╔══════════════════════════════════════════════════════════════╗
# β•‘  EDIT YOUR SUPABASE KEYS HERE  (or set as HF secrets)      β•‘
# ╠══════════════════════════════════════════════════════════════╣
# β•‘                                                             β•‘
SUPABASE_URL    = ""   # e.g. "https://xxxx.supabase.co"
SUPABASE_KEY    = ""   # Service Role Key (not anon key)
SUPABASE_BUCKET = "antigravity-data"  # Bucket name
# β•‘                                                             β•‘
# β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•

# --- Env vars override hardcoded values above ---
SUPABASE_URL    = os.environ.get("SUPABASE_URL",    SUPABASE_URL)
SUPABASE_KEY    = os.environ.get("SUPABASE_KEY",    SUPABASE_KEY)
SUPABASE_BUCKET = os.environ.get("SUPABASE_BUCKET", SUPABASE_BUCKET)

# --- Config ---
DATA_DIR         = "/root/.antigravity_tools"
BACKUP_FILENAME  = "antigravity_backup.tar.gz"
SYNC_INTERVAL    = 60   # seconds between change checks
APP_BINARY       = "/app/antigravity-tools"

# --- Logging ---
logging.basicConfig(
    level=logging.INFO,
    format="[%(asctime)s] [SYNC] %(message)s",
    datefmt="%H:%M:%S",
)
log = logging.getLogger("sync")

# --- Global state ---
_last_hash = ""
_app_process = None

# ================================================================
#  SUPABASE STORAGE HELPERS
# ================================================================

try:
    import requests as http
except ImportError:
    log.error("'requests' module not found. Install it: pip install requests")
    log.error("Sync will be DISABLED. The app will still run.")
    http = None


def _supabase_ok():
    """Check if Supabase is configured."""
    if not SUPABASE_URL or not SUPABASE_KEY:
        return False
    if http is None:
        return False
    return True


def _headers():
    return {
        "Authorization": f"Bearer {SUPABASE_KEY}",
        "apikey": SUPABASE_KEY,
    }


def _obj_url(path):
    return f"{SUPABASE_URL.rstrip('/')}/storage/v1/object/{path}"


# ================================================================
#  SYNC OPERATIONS
# ================================================================

def dir_hash():
    """Hash all file paths + sizes + mtimes to detect changes."""
    if not os.path.exists(DATA_DIR):
        return ""
    h = hashlib.sha256()
    for root, dirs, files in os.walk(DATA_DIR):
        dirs.sort()
        for f in sorted(files):
            fp = os.path.join(root, f)
            rel = os.path.relpath(fp, DATA_DIR)
            try:
                st = os.stat(fp)
                h.update(f"{rel}:{st.st_size}:{st.st_mtime_ns}".encode())
            except OSError:
                pass
    return h.hexdigest()


def sync_down():
    """Download backup from Supabase and extract to DATA_DIR."""
    if not _supabase_ok():
        log.info("Supabase not configured. Skipping restore.")
        return False

    log.info(f"Downloading backup from Supabase '{SUPABASE_BUCKET}'...")
    try:
        r = http.get(
            _obj_url(f"{SUPABASE_BUCKET}/{BACKUP_FILENAME}"),
            headers=_headers(),
            timeout=30,
        )
    except Exception as e:
        log.error(f"Download failed: {e}")
        return False

    if r.status_code in (400, 404):
        log.info("No backup found. Starting fresh.")
        return False

    if r.status_code != 200:
        log.error(f"Download error: HTTP {r.status_code}")
        return False

    # Extract
    tmp = tempfile.mktemp(suffix=".tar.gz")
    try:
        with open(tmp, "wb") as f:
            f.write(r.content)
        os.makedirs(DATA_DIR, exist_ok=True)
        with tarfile.open(tmp, "r:gz") as tar:
            tar.extractall(path=DATA_DIR)
        count = sum(1 for _ in _walk_files())
        log.info(f"βœ… Restored {count} files from backup.")
        return True
    except Exception as e:
        log.error(f"Extract failed: {e}")
        return False
    finally:
        if os.path.exists(tmp):
            os.unlink(tmp)


def sync_up():
    """Tar DATA_DIR and upload to Supabase."""
    if not _supabase_ok():
        return False

    if not os.path.exists(DATA_DIR):
        return False

    files = list(_walk_files())
    if not files:
        return False

    log.info(f"Uploading backup ({len(files)} files)...")
    tmp = tempfile.mktemp(suffix=".tar.gz")
    try:
        # Create tar
        with tarfile.open(tmp, "w:gz") as tar:
            for fp in files:
                arcname = os.path.relpath(fp, DATA_DIR)
                tar.add(fp, arcname=arcname)
        size_kb = os.path.getsize(tmp) / 1024
        log.info(f"Tarball: {size_kb:.1f} KB")

        # Upload (upsert)
        url = _obj_url(f"{SUPABASE_BUCKET}/{BACKUP_FILENAME}")
        headers = _headers()
        headers["Content-Type"] = "application/gzip"
        headers["x-upsert"] = "true"

        with open(tmp, "rb") as f:
            r = http.post(url, headers=headers, data=f, timeout=60)

        # Fallback to PUT if POST fails
        if r.status_code == 400:
            with open(tmp, "rb") as f:
                r = http.put(url, headers=headers, data=f, timeout=60)

        if r.status_code in (200, 201):
            log.info("βœ… Backup uploaded.")
            return True
        else:
            log.error(f"Upload failed: HTTP {r.status_code} β€” {r.text[:200]}")
            return False
    except Exception as e:
        log.error(f"Upload error: {e}")
        return False
    finally:
        if os.path.exists(tmp):
            os.unlink(tmp)


def _walk_files():
    """Yield all file paths in DATA_DIR."""
    if not os.path.exists(DATA_DIR):
        return
    for root, _, files in os.walk(DATA_DIR):
        for f in files:
            yield os.path.join(root, f)


# ================================================================
#  WATCHER (background thread)
# ================================================================

def watcher_loop(stop_event):
    """Every SYNC_INTERVAL seconds, check for changes and sync."""
    global _last_hash

    # Wait for the app to create the data dir
    waited = 0
    while not os.path.exists(DATA_DIR) and waited < 120:
        time.sleep(5)
        waited += 5

    # Initial backup after app starts
    time.sleep(10)
    sync_up()
    _last_hash = dir_hash()

    while not stop_event.is_set():
        stop_event.wait(SYNC_INTERVAL)
        if stop_event.is_set():
            break

        current = dir_hash()
        if current != _last_hash:
            log.info("Changes detected. Syncing...")
            if sync_up():
                _last_hash = current


# ================================================================
#  MAIN β€” orchestrates everything
# ================================================================

def main():
    global _app_process

    print("=" * 50)
    print("  Antigravity Manager + Supabase Sync")
    print("=" * 50)

    # Show config status
    if _supabase_ok():
        print(f"  Supabase: βœ… Configured ({SUPABASE_URL[:40]}...)")
        print(f"  Bucket:   {SUPABASE_BUCKET}")
    else:
        print("  Supabase: ❌ Not configured")
        if not SUPABASE_URL:
            print("    β†’ SUPABASE_URL is empty")
        if not SUPABASE_KEY:
            print("    β†’ SUPABASE_KEY is empty")
        if http is None:
            print("    β†’ 'requests' module not installed")
        print("  ⚠️  Data will NOT persist across restarts!")
    print("=" * 50)
    print()

    # Step 1: Restore backup
    sync_down()

    # Step 2: Start background watcher
    stop_event = threading.Event()
    if _supabase_ok():
        watcher = threading.Thread(target=watcher_loop, args=(stop_event,), daemon=True)
        watcher.start()
        log.info(f"Watcher started (every {SYNC_INTERVAL}s)")

    # Step 3: Start the app
    log.info("Starting Antigravity Manager...")
    _app_process = subprocess.Popen(
        [APP_BINARY, "--headless"],
        stdout=sys.stdout,
        stderr=sys.stderr,
    )

    # Handle shutdown
    def shutdown(signum, frame):
        log.info("Shutting down...")
        stop_event.set()

        # Final backup
        if _supabase_ok():
            log.info("Running final backup...")
            sync_up()
            log.info("Final backup done.")

        # Stop the app
        if _app_process and _app_process.poll() is None:
            _app_process.terminate()
            try:
                _app_process.wait(timeout=10)
            except subprocess.TimeoutExpired:
                _app_process.kill()

        sys.exit(0)

    signal.signal(signal.SIGTERM, shutdown)
    signal.signal(signal.SIGINT, shutdown)

    # Wait for app to exit
    try:
        _app_process.wait()
    except KeyboardInterrupt:
        shutdown(None, None)


if __name__ == "__main__":
    main()