#!/bin/bash
set -euo pipefail

# ------------------------------------------------------------------
# trust-devices.sh — Trigger ADB trust dialog on multiple devices
#
# Connects to each device so it shows the "Allow USB debugging?"
# dialog. Accept the dialog on each device to permanently trust
# this computer.
#
# Usage:
#   ./trust-devices.sh [devices]
#
# Arguments:
#   devices   Comma-separated IPs, or a file with one IP per line
#             (default: devices.txt)
#
# Examples:
#   ./trust-devices.sh
#   ./trust-devices.sh 192.168.1.101,192.168.1.102,192.168.1.103
#   ./trust-devices.sh my-devices.txt
# ------------------------------------------------------------------

ADB_PORT=5555
DEVICE_ARG="${1:-devices.txt}"

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
CYAN='\033[0;36m'
NC='\033[0m'

trusted=0
failed=0
failed_devices=()

# --- Load device IPs ---
load_devices() {
    local devices=()

    if [[ "$DEVICE_ARG" =~ ^[0-9.,]+$ ]]; then
        IFS=',' read -ra devices <<< "$DEVICE_ARG"
    elif [[ -f "$DEVICE_ARG" ]]; then
        while IFS= read -r line || [[ -n "$line" ]]; do
            line="${line%%#*}"
            line="${line// /}"
            [[ -z "$line" ]] && continue
            devices+=("$line")
        done < "$DEVICE_ARG"
    else
        echo -e "${RED}Not a file or comma-separated IPs: $DEVICE_ARG${NC}"
        echo ""
        echo "Pass IPs directly:"
        echo "  ./trust-devices.sh 192.168.1.101,192.168.1.102"
        echo ""
        echo "Or create a file with one IP per line:"
        echo "  echo '192.168.1.101' >> devices.txt"
        echo "  echo '192.168.1.102' >> devices.txt"
        exit 1
    fi

    if [[ ${#devices[@]} -eq 0 ]]; then
        echo -e "${RED}No devices found${NC}"
        exit 1
    fi

    printf '%s\n' "${devices[@]}"
}

# --- Trust one device ---
trust_device() {
    local ip="$1"
    local target="$ip:$ADB_PORT"

    echo -e "\n${YELLOW}[$ip]${NC} Connecting..."

    # Connect
    if ! adb connect "$target" 2>&1 | grep -q "connected"; then
        sleep 2
        if ! adb connect "$target" 2>&1 | grep -q "connected"; then
            echo -e "${RED}[$ip] Connection failed${NC}"
            return 1
        fi
    fi

    # Check if already authorized
    local status
    status=$(adb -s "$target" get-state 2>&1 || true)

    if [[ "$status" == "device" ]]; then
        echo -e "${GREEN}[$ip] Already trusted${NC}"
        adb disconnect "$target" 2>/dev/null
        return 0
    fi

    # Device connected but not yet trusted — wait for user to accept
    echo -e "${CYAN}[$ip] Trust dialog should be showing on the device${NC}"
    echo -e "${CYAN}[$ip] Accept the dialog, then press Enter here to continue...${NC}"
    read -r

    # Verify authorization
    status=$(adb -s "$target" get-state 2>&1 || true)
    if [[ "$status" == "device" ]]; then
        echo -e "${GREEN}[$ip] Trusted successfully${NC}"
        adb disconnect "$target" 2>/dev/null
        return 0
    else
        echo -e "${RED}[$ip] Still unauthorized — check the device screen${NC}"
        adb disconnect "$target" 2>/dev/null
        return 1
    fi
}

# --- Main ---
echo "=== Fishbowl Device Trust Setup ==="
echo "This will connect to each device to trigger the ADB trust dialog."
echo "You will need to accept the dialog on each device's screen."
echo ""

DEVICES=()
while IFS= read -r line; do
    DEVICES+=("$line")
done < <(load_devices)
echo "Devices: ${#DEVICES[@]}"

for ip in "${DEVICES[@]}"; do
    if trust_device "$ip"; then
        ((trusted++))
    else
        ((failed++))
        failed_devices+=("$ip")
    fi
done

# --- Summary ---
echo ""
echo "=== Trust Setup Complete ==="
echo -e "${GREEN}Trusted: $trusted${NC}"
if [[ $failed -gt 0 ]]; then
    echo -e "${RED}Failed: $failed${NC}"
    for ip in "${failed_devices[@]}"; do
        echo -e "  ${RED}- $ip${NC}"
    done
fi