set -u
S=$SCRATCH; W=$CHECKOUT
R=$S/run-$(date +%s); mkdir -p $R
E=$W/apps/desktop/node_modules/electron/dist/electron
export T3CODE_HOME=$R/home XDG_CONFIG_HOME=$R/xdg-config T3CODE_DEV_SEED=0
unset VITE_DEV_SERVER_URL ELECTRON_RUN_AS_NODE
CAT='JSON.stringify({schemaVersion:1,targets:[],profiles:[],credentials:[],remoteDpopTokens:[],disabledEnvironmentIds:["synthetic-env-1"]})'
launch() { "$E" --no-sandbox --disable-gpu --remote-debugging-port=9433 "$2" > $R/$1.log 2>&1 & APP_PID=$!; }
stop() { kill $APP_PID 2>/dev/null; wait $APP_PID 2>/dev/null; }
echo "== 1. source-build identity (app dir apps/desktop, productName 'T3 Code (Beta)') saves a catalog"
launch source-write $W/apps/desktop
node $S/cdp.mjs 9433 "window.desktopBridge.setConnectionCatalog($CAT).then(ok => window.desktopBridge.getConnectionCatalog().then(c => ({ok, readBack: c, name: navigator.userAgent})))"; stop
echo "== keyring entries"; secret-tool search --all xdg:schema chrome_libsecret_os_crypt_password_v2 2>&1 | grep -i "application" 
echo "== 2. packaged identity ({\"name\":\"t3code\"}, like the AppImage) reads it"
launch packaged-read $S/staged
node $S/cdp.mjs 9433 "window.desktopBridge.getConnectionCatalog().then(c => ({ok:true, c}), e => ({error: String(e)}))"; stop
echo "== keyring entries"; secret-tool search --all xdg:schema chrome_libsecret_os_crypt_password_v2 2>&1 | grep -i "application"
echo "== 3. back to source identity"
launch source-reread $W/apps/desktop
node $S/cdp.mjs 9433 "window.desktopBridge.getConnectionCatalog().then(c => ({ok:true, c}), e => ({error: String(e)}))"; stop
echo "== trace errors (packaged run)"; grep -rho "ElectronSafeStorageDecryptError\|DesktopConnectionCatalogStoreProtectionError[^\"]*" $R/home 2>/dev/null | sort | uniq -c | head
echo RUN=$R
