import './lib/bare-globals.js'
import Hyperswarm from 'hyperswarm'
import crypto from 'hypercore-crypto'
import b4a from 'b4a'
import c from 'compact-encoding'
import ProtomuxRPC from 'protomux-rpc'
const ck = globalThis.Bare.argv[2]
const swarm = new Hyperswarm({ keyPair: crypto.keyPair(crypto.hash(b4a.from('gs2-' + ck))) })
const done = new Promise((res, rej) => { const to = setTimeout(() => rej(new Error('timeout')), 15000)
swarm.on('connection', async conn => { if (b4a.toString(conn.remotePublicKey, 'hex') !== ck) return
const rpc = new ProtomuxRPC(conn, { protocol: 'hyper-proto-peer/device/v1', valueEncoding: c.json })
try { const s = await rpc.request('get-state', {}); clearTimeout(to); res(s) } catch (e) { clearTimeout(to); rej(e) } }) })
swarm.join(b4a.from(ck, 'hex'), { client: true, server: true }); await swarm.flush()
try { const s = await done; console.log('STATE holdsLease=' + s.holdsLease + ' headRev=' + (s.head && s.head.rev) + ' records=' + (s.records || []).length) } catch (e) { console.log('FAIL ' + e.message) }
await swarm.destroy(); globalThis.Bare.exit(0)