#!/bin/bash # Ensure HF CLI is in PATH export PATH="$HOME/.local/bin:$PATH" # Set HF Token from Space Secrets export HF_TOKEN="${HF_TOKEN}" # Variables BUCKET='hf://buckets/bk939448/opencodeai' SOURCE='/home' # Configure Git git config --global user.email 'badal@example.com' git config --global user.name 'Badal' # Set OpenCode path OP_PATH=$(find / -name opencode -type f -printf '%h' -quit 2>/dev/null) export PATH="$OP_PATH:$PATH" # ============================================ # STEP 0: BUCKET CLEANUP (Delete .cache & .npm from bucket) # ============================================ echo '=== [STEP 0] CLEANING BUCKET (Removing .cache and .npm) ===' hf buckets rm "$BUCKET/.cache" --recursive -y 2>/dev/null && echo '=== [STEP 0] .cache removed from bucket ===' || echo '=== [STEP 0] .cache not found in bucket (skipping) ===' hf buckets rm "$BUCKET/.npm" --recursive -y 2>/dev/null && echo '=== [STEP 0] .npm removed from bucket ===' || echo '=== [STEP 0] .npm not found in bucket (skipping) ===' echo '=== [STEP 0] BUCKET CLEANUP DONE ===' # ============================================ # STEP 1: RESTORE (Try, but continue if bucket empty) # ============================================ echo '=== [STEP 1] RESTORING DATA FROM BUCKET ===' if hf sync "$BUCKET" "$SOURCE" --delete 2>/dev/null; then echo '=== [STEP 1] RESTORE COMPLETE ===' else echo '=== [STEP 1] Restore skipped (bucket empty or failed - continuing anyway) ===' fi # Auto-create /home/user if not exists if [ ! -d "/home/user" ]; then echo '=== Creating /home/user folder ===' mkdir -p /home/user fi # ============================================ # STEP 2: START OPENCODE # ============================================ echo '=== [STEP 2] STARTING OPENCODE ===' export OPENCODE_SERVER_USERNAME=${OPENCODE_SERVER_USERNAME} export OPENCODE_SERVER_PASSWORD=${OPENCODE_SERVER_PASSWORD} opencode web --port 7860 --hostname 0.0.0.0 > /tmp/opencode.log 2>&1 & sleep 10 echo '=== [STEP 2] OPENCODE STARTED ===' # ============================================ # STEP 3: INOTIFY-BASED SMART SYNC # ============================================ echo '=== [STEP 3] STARTING SMART SYNC (inotifywait) ===' while true; do # Check if OpenCode is still running if ! pgrep -f 'opencode' > /dev/null; then echo 'CRITICAL: OpenCode process died! Exiting container...' exit 1 fi # Wait for any file change in /home (blocks until change detected) # Excludes .mdb files, .cache folder, .npm folder from triggering sync inotifywait -r -e modify,create,delete,move \ --exclude '.*\.mdb$' \ --exclude '.*/\.cache(/.*)?$' \ --exclude '.*/\.npm(/.*)?$' \ -q "$SOURCE" # Change detected! Sync to bucket (excluding .mdb, .cache, .npm) echo "=== [STEP 3] Change detected! Syncing to bucket... ===" hf sync "$SOURCE" "$BUCKET" --delete --exclude "*.mdb" echo "=== [STEP 3] Sync done! Waiting for next change... ===" done