#!/usr/bin/env bash
set -euo pipefail

if ! command -v nostrfs >/dev/null 2>&1; then
  echo "nostrfs not found; skipping test" >&2
  exit 0
fi

if [ ! -e /dev/fuse ]; then
  echo "/dev/fuse not present; skipping test" >&2
  exit 0
fi

PY=$(command -v python3 || true)
if [ -z "$PY" ]; then
  echo "python3 not found; skipping test" >&2
  exit 0
fi

MNT="$(mktemp -d /tmp/nostrfs-wb.XXXXXX)"
ETC_CONF="/etc/nss_nostr.conf"
DB_PATH="/tmp/nostr_cache.db"
CAS_DIR="/var/cache/nostrfs/$(id -u)"
mkdir -p "$(dirname "$ETC_CONF")" || true
mkdir -p "$CAS_DIR"
cat > "$ETC_CONF" <<CONF
db_path=$DB_PATH
uid_base=100000
uid_range=100000
CONF

if command -v sqlite3 >/dev/null 2>&1; then
  sqlite3 "$DB_PATH" <<SQL
PRAGMA journal_mode=WAL;
CREATE TABLE IF NOT EXISTS users( uid INTEGER PRIMARY KEY, npub TEXT UNIQUE, username TEXT UNIQUE, gid INTEGER, home TEXT, updated_at INTEGER);
CREATE TABLE IF NOT EXISTS blobs( cid TEXT PRIMARY KEY, size INTEGER, mtime INTEGER, path TEXT, present INTEGER);
CREATE TABLE IF NOT EXISTS settings(key TEXT PRIMARY KEY, value TEXT);
INSERT OR REPLACE INTO settings(key,value) VALUES('warmcache','1');
INSERT OR REPLACE INTO settings(key,value) VALUES('manifest.personal','{"version":2,"entries":[],"links":[]}');
SQL
else
  echo "sqlite3 not found; skipping test" >&2
  exit 0
fi

cleanup() {
  set +e
  if mountpoint -q "$MNT"; then
    if command -v fusermount3 >/dev/null 2>&1; then
      fusermount3 -u "$MNT" || true
    else
      umount "$MNT" || true
    fi
  fi
  rmdir "$MNT" 2>/dev/null || true
  if [ -n "${FAKE_PID:-}" ]; then kill "$FAKE_PID" 2>/dev/null || true; fi
}
trap cleanup EXIT INT TERM

# Start fake Blossom on 127.0.0.1:8081
export FAKE_BLOSSOM_PORT=8081
export FAKE_BLOSSOM_DIR=/tmp/fake_blossom
mkdir -p "$FAKE_BLOSSOM_DIR"
"$PY" "$(dirname "$0")/fake_blossom.py" &
FAKE_PID=$!
sleep 0.3

export BLOSSOM_BASE_URL="http://127.0.0.1:${FAKE_BLOSSOM_PORT}"
# Avoid real relay traffic
export RELAYS_DEFAULT="wss://127.0.0.1:65535"

nostrfs --writeback "$MNT" &
PID=$!
sleep 1

if ! mountpoint -q "$MNT"; then
  echo "nostrfs did not mount at $MNT" >&2
  kill "$PID" 2>/dev/null || true
  exit 1
fi

echo -n "abc123" > "$MNT/file.txt"
sync
sleep 1

MANIFEST_JSON="$(sqlite3 "$DB_PATH" "select value from settings where key='manifest.personal';")"
echo "$MANIFEST_JSON" | grep -q '"path":"/file.txt"' || { echo "manifest did not include /file.txt" >&2; exit 1; }
CID=$(echo "$MANIFEST_JSON" | sed -n 's/.*"path":"\/file.txt"[^}]*"cid":"\([^"]\+\)".*/\1/p' | head -n1)
[ -n "$CID" ] || { echo "failed to extract CID" >&2; exit 1; }

if [ -f "$CAS_DIR/$CID" ]; then
  echo "CAS ok: $CAS_DIR/$CID"
else
  echo "CAS missing: $CAS_DIR/$CID" >&2
  exit 1
fi

if command -v fusermount3 >/dev/null 2>&1; then
  fusermount3 -u "$MNT"
else
  umount "$MNT"
fi

wait "$PID" 2>/dev/null || true
exit 0
