================================================================================
RBIO-Mesh-Kit: Phone Setup Guide (GrapheneOS & /e/OS)
================================================================================
Version: 1.0
Target Devices: Google Pixel (GrapheneOS) or Samsung/Xiaomi (/e/OS)
Author: RBIO Project

This guide walks you through turning a cheap Android phone into an RBIO mesh
node. Choose Section A for GrapheneOS or Section B for /e/OS.

--------------------------------------------------------------------------------
TABLE OF CONTENTS
--------------------------------------------------------------------------------
1. Before You Begin
2. Section A: GrapheneOS Setup (Google Pixel)
3. Section B: /e/OS Setup (Samsung/Xiaomi)
4. Common Steps: Termux & RBIO Scripts
5. Connecting to the Pi
6. Testing the Mesh
7. Troubleshooting

--------------------------------------------------------------------------------
1. BEFORE YOU BEGIN
--------------------------------------------------------------------------------
- Ensure your Raspberry Pi 5 is already running (see pi-setup-guide.txt).
- Note your Pi's IP address (e.g., 192.168.1.50).
- Have a USB cable to connect the phone to your computer for flashing.
- Back up any data on the phone. Flashing WILL erase everything.

WARNING: Do not use a phone tied to your personal Google account or carrier.
Buy used, unlocked devices with cash if possible.

--------------------------------------------------------------------------------
2. SECTION A: GRAPHENEOS SETUP (GOOGLE PIXEL)
--------------------------------------------------------------------------------
Supported Devices: Pixel 6a, Pixel 7, Pixel 7a, Pixel 8

STEP 1: Unlock the Bootloader
1. Enable Developer Options on the phone:
   Settings > About Phone > Tap "Build Number" 7 times.
2. Enable OEM Unlocking:
   Settings > System > Developer Options > OEM Unlocking = ON
3. Connect phone to computer via USB.
4. Open a terminal on your computer and run:
   adb reboot bootloader
5. On the phone, unlock the bootloader:
   fastboot flashing unlock
6. Confirm on the phone screen (use volume keys + power).

STEP 2: Flash GrapheneOS
1. Visit: https://grapheneos.org/install
2. Follow the web installer instructions for your specific Pixel model.
3. The process typically involves:
   - Opening the web installer in Chrome/Brave.
   - Connecting the phone in bootloader mode.
   - Clicking "Unlock Bootloader" then "Flash Release".
4. Wait 10-15 minutes for the flash to complete.
5. Lock the bootloader again (optional but recommended for security):
   fastboot flashing lock

STEP 3: Initial Device Setup
1. Boot the phone.
2. Skip all Google prompts (GrapheneOS has no Google services).
3. Connect to your Wi-Fi network (same network as the Pi).
4. Do NOT insert a SIM card if running Wi-Fi-only mode.

STEP 4: Install F-Droid
1. Open the GrapheneOS browser (Vanadium).
2. Go to: https://f-droid.org
3. Download and install the F-Droid APK.
4. Open F-Droid and let it update repositories.

STEP 5: Install Required Apps from F-Droid
1. Open F-Droid.
2. Search for and install:
   - Termux
   - Termux:API (required for Wi-Fi and location commands)
3. Do NOT install Termux from the Google Play Store. It is outdated.

STEP 6: Grant Permissions
1. Go to Settings > Apps > Termux.
2. Grant:
   - Location: Allow all the time
   - Wi-Fi: Allow
3. Repeat for Termux:API.

Proceed to Section 4: Common Steps.

--------------------------------------------------------------------------------
3. SECTION B: /E/OS SETUP (SAMSUNG/XIAOMI)
--------------------------------------------------------------------------------
Supported Devices: Samsung Galaxy A51, A52, A53, Xiaomi Redmi Note 10, Fairphone 3

STEP 1: Check Device Compatibility
1. Visit: https://doc.e.foundation
2. Search for your device model.
3. Download the correct build and recovery image.

STEP 2: Unlock the Bootloader
This varies by manufacturer. General steps:

For Samsung:
1. Enable Developer Options (tap Build Number 7 times).
2. Enable OEM Unlocking in Developer Options.
3. Power off. Hold Volume Up + Power to enter Download Mode.
4. Long-press Volume Up to unlock.

For Xiaomi:
1. Enable Developer Options.
2. Enable OEM Unlocking.
3. Bind your device in Mi Unlock tool (requires a Mi account, use a burner).
4. Boot to Fastboot mode (Volume Down + Power).
5. Use Mi Unlock tool on your computer.

STEP 3: Flash /e/OS
1. Follow the official /e/OS installation guide for your device:
   https://doc.e.foundation/installation
2. The process typically involves:
   - Downloading the /e/OS ROM and recovery image.
   - Booting into Fastboot mode.
   - Flashing the recovery image.
   - Booting into recovery.
   - Sideload the /e/OS ROM.
3. Wait 15-30 minutes for the flash to complete.
4. Reboot.

STEP 4: Initial Device Setup
1. Boot the phone.
2. /e/OS will guide you through setup. Skip any optional cloud services.
3. Connect to your Wi-Fi network (same network as the Pi).
4. Do NOT insert a SIM card if running Wi-Fi-only mode.

STEP 5: Install Required Apps
/e/OS comes with "App Lounge" (their app store).
1. Open App Lounge.
2. Search for and install:
   - Termux
   - Termux:API
3. (Optional) Install MacroDroid for automation:
   - Search for "MacroDroid" in App Lounge or F-Droid.

STEP 6: Grant Permissions
1. Go to Settings > Apps > Termux.
2. Grant:
   - Location: Allow all the time
   - Wi-Fi: Allow
3. Repeat for Termux:API.

Proceed to Section 4: Common Steps.

--------------------------------------------------------------------------------
4. COMMON STEPS: TERMUX & RBIO SCRIPTS
--------------------------------------------------------------------------------
These steps are the same for both GrapheneOS and /e/OS.

STEP 1: Transfer RBIO Files to the Phone
Option A: Via USB
1. Connect phone to computer via USB.
2. Copy the "phones/graphene" or "phones/eos" folder to the phone's
   Downloads folder.

Option B: Via Local Network
1. On the Pi, start a simple HTTP server:
   cd ~/rbio-mesh/phones/graphene
   python3 -m http.server 8080
2. On the phone, open the browser and go to:
   http://192.168.1.50:8080
3. Download each file: termux-bootstrap.sh, heartbeat.py, role-swap.sh

STEP 2: Run the Bootstrap Script
1. Open Termux on the phone.
2. Navigate to the folder where you saved the files:
   cd /sdcard/Download
   (Or wherever you placed them)
3. Move files to Termux's home directory:
   cp termux-bootstrap.sh heartbeat.py role-swap.sh $HOME/
4. Navigate home:
   cd $HOME
5. Run the bootstrap script:
   sh termux-bootstrap.sh
6. Wait for packages to install (2-5 minutes).

STEP 3: Configure the Phone
1. Edit the configuration file:
   nano $HOME/rbio-mesh/config.json
2. Set the following values:
   - "pi_ip_address": "192.168.1.50"  (Your Pi's actual IP)
   - "device_id": "phone-01"  (A unique name for this phone)
3. Save and exit (Ctrl+X, then Y, then Enter).

STEP 4: Enroll the Phone with the Pi
1. In Termux, run:
   curl -X POST http://192.168.1.50:5000/enroll -H "Content-Type: application/json" -d '{"device_id": "phone-01"}'
2. You should receive a response with your assigned role:
   {"role_name": "Courier", "role_key": "uuid-xxxx", ...}
3. If you see this, the phone is enrolled successfully.

STEP 5: Start the Heartbeat
1. In Termux, run:
   python3 $HOME/rbio-mesh/heartbeat.py
2. You should see:
   "Connected to RBIO Mesh!"
   "Heartbeat loop running..."
3. Leave Termux running. Do not close it.

STEP 6: (Optional) Set Up Auto-Start on Boot

For GrapheneOS (using Termux Boot):
1. Install "Termux:Boot" from F-Droid.
2. Create a boot script:
   mkdir -p $HOME/.termux/boot
   echo '#!/bin/sh' > $HOME/.termux/boot/rbio-start.sh
   echo 'python3 $HOME/rbio-mesh/heartbeat.py &' >> $HOME/.termux/boot/rbio-start.sh
   chmod +x $HOME/.termux/boot/rbio-start.sh
3. Open Termux:Boot once, then reboot. The heartbeat will start automatically.

For /e/OS (using MacroDroid):
1. Open MacroDroid.
2. Create a new Macro:
   - Trigger: Device Boot
   - Action: Run Shell Script
     Command: python3 /data/data/com.termux/files/home/rbio-mesh/heartbeat.py
     Check "Run as root" if available, otherwise use Termux integration.
3. Save and enable the Macro.

--------------------------------------------------------------------------------
5. CONNECTING TO THE PI
--------------------------------------------------------------------------------
1. Ensure the phone and Pi are on the SAME Wi-Fi network.
2. Test connectivity:
   In Termux, run:
   ping 192.168.1.50
   (Replace with your Pi's IP)
   You should see responses.

3. If ping fails:
   - Check Wi-Fi connection on both devices.
   - Check Pi firewall: sudo ufw allow 1883, sudo ufw allow 5000
   - Try restarting the Pi's Docker stack: docker compose restart

--------------------------------------------------------------------------------
6. TESTING THE MESH
--------------------------------------------------------------------------------
Once the heartbeat is running, test a manual role swap:

1. On your computer, open a browser and go to:
   http://192.168.1.50:5000/trigger-swap/phone-01

2. On the phone, check Termux. You should see:
   "Received Swap Command: Switching to 'Relay'..."

3. Check the swap log:
   cat $HOME/rbio-mesh/swap.log

4. Check the Pi's database:
   On the Pi, run:
   docker compose exec rbio-server sqlite3 /data/roles.db "SELECT * FROM roles;"

5. Verify the role has changed in the database.

Congratulations. Your RBIO mesh node is operational.

--------------------------------------------------------------------------------
7. TROUBLESHOOTING
--------------------------------------------------------------------------------
Problem: "Permission denied" when running heartbeat.py
Solution: Run 'chmod +x heartbeat.py' in Termux.

Problem: "Config file not found"
Solution: Ensure config.json is in the same directory as heartbeat.py.
The script looks for config.json in its own directory.

Problem: "Connection refused" to the Pi
Solution: Check that Docker containers are running on the Pi.
Run 'docker compose ps' on the Pi.

Problem: Heartbeat sends but no swap happens
Solution: Check your thresholds.json on the Pi.
The default time trigger is 48 hours. For testing, lower it to 1 minute:
"max_role_duration_hours": 0.02

Problem: Termux closes when phone sleeps
Solution: Acquire a wake lock:
In Termux, run: termux-wake-lock
This keeps Termux running in the background.

Problem: GPS/Location returns 0.0
Solution: Ensure Termux has "Allow all the time" location permission.
Go to Settings > Apps > Termux > Permissions > Location.

================================================================================
END OF PHONE SETUP GUIDE
================================================================================