# Raspberry Pi Implementation Draft

This is a concrete implementation plan for Pi-based piNail onboarding.

## Components
- `Flask` app (already present in `piNail2`) for setup endpoints/pages.
- `hostapd` for AP mode.
- `dnsmasq` for DHCP + captive DNS in setup mode.
- `avahi-daemon` for `pinail.local` mDNS in normal mode.

## Modes
- `normal`:
  - Connect to configured WiFi.
  - Run control server at `0.0.0.0:5000`.
- `setup`:
  - Start AP on wlan0 (`192.168.4.1/24`).
  - Start captive portal UI.

## Suggested State Rules
- Enter setup mode when:
  - no wifi config exists, or
  - join fails N times over T seconds, or
  - user holds setup/reset button at boot.
- Exit setup mode when:
  - credentials validate and connection succeeds.

## Boot Sequence
1. Start `pinail-network-bootstrap.service` (Before `pinail2.service`).
2. Bootstrap checks `/home/pi/piNail2/wifi_config.json`.
3. If valid and connectable, ensure normal mode and continue boot.
4. If not, bring up setup mode and start setup UI.

## Setup AP Parameters (draft)
- SSID: `piNail-Setup-<last4mac>`
- Security: WPA2 PSK (device label) or open AP (if easier UX).
- AP IP: `192.168.4.1`
- DHCP range: `192.168.4.20-192.168.4.120`

## Captive Portal Endpoints (draft)
- `GET /setup`: setup form page
- `POST /setup`: submit WiFi/network settings
- `GET /setup/status`: async connection progress
- `POST /setup/reset`: clear saved creds and return to setup mode

## Config Write Path
1. Validate form values server-side.
2. Write to temp file then atomic rename:
   - `/home/pi/piNail2/wifi_config.json.tmp`
   - `/home/pi/piNail2/wifi_config.json`
3. Apply network config.
4. Show success page with hostname and assigned IP.
5. Reboot or restart networking services.

## Normal Mode Addressing
- Primary URL: `http://pinail.local:5000`
- Secondary URL: `http://<dhcp-ip>:5000`
- Optional static mode if user enters:
  - IP
  - subnet
  - gateway
  - DNS

## Security Notes
- Do not log WiFi password.
- Restrict setup endpoints to setup mode only.
- Optionally disable setup AP once normal mode succeeds.
