#!/bin/bash
set -euo pipefail

# ------------------------------------------------------------------
# deploy.sh — Deploy Fishbowl APK to Android devices over ADB WiFi
#
# Usage:
#   ./deploy.sh <apk-url-or-path> [devices]
#
# Arguments:
#   apk-url-or-path   URL to download or local path to the APK
#   devices            Comma-separated IPs, or a file with one IP per line
#                      (default: devices.txt)
#
# Examples:
#   ./deploy.sh https://files.fishbowlmeetings.com/fishbowl_latest.apk
#   ./deploy.sh ./fishbowl.apk 192.168.1.101,192.168.1.102,192.168.1.103
#   ./deploy.sh https://example.com/app.apk my-devices.txt
# ------------------------------------------------------------------

ADB_PORT=5555
TIMEOUT=10
APK_SOURCE="${1:?Usage: ./deploy.sh <apk-url-or-path> [devices]}"
DEVICE_ARG="${2:-devices.txt}"

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

passed=0
failed=0
failed_devices=()

# --- Resolve APK to a local file ---
resolve_apk() {
    if [[ "$APK_SOURCE" == http* ]]; then
        local tmp
        tmp=$(mktemp -d)/fishbowl.apk
        echo -e "${YELLOW}Downloading APK...${NC}" >&2
        if ! curl -fSL --progress-bar -o "$tmp" "$APK_SOURCE"; then
            echo -e "${RED}Failed to download APK from $APK_SOURCE${NC}" >&2
            exit 1
        fi
        echo "$tmp"
    elif [[ -f "$APK_SOURCE" ]]; then
        echo "$APK_SOURCE"
    else
        echo -e "${RED}APK not found: $APK_SOURCE${NC}" >&2
        exit 1
    fi
}

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

    if [[ "$DEVICE_ARG" =~ ^[0-9.,]+$ ]]; then
        # Single IP or comma-separated IPs
        IFS=',' read -ra devices <<< "$DEVICE_ARG"
    elif [[ -f "$DEVICE_ARG" ]]; then
        # File with one IP per line
        while IFS= read -r line || [[ -n "$line" ]]; do
            line="${line%%#*}"        # strip comments
            line="${line// /}"        # strip spaces
            [[ -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 "  ./deploy.sh app.apk 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[@]}"
}

# --- Deploy to one device ---
deploy_device() {
    local ip="$1"
    local apk="$2"
    local target="$ip:$ADB_PORT"

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

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

    # Wait for device to be ready
    if ! adb -s "$target" wait-for-device 2>/dev/null; then
        echo -e "${RED}[$ip] Device not ready${NC}"
        adb disconnect "$target" 2>/dev/null
        return 1
    fi

    # Install APK (-r = replace existing, -d = allow downgrade)
    echo -e "${YELLOW}[$ip]${NC} Installing APK..."
    local result
    result=$(adb -s "$target" install -r -d "$apk" 2>&1)
    echo "  $result"
    if echo "$result" | grep -q "Success"; then
        echo -e "${GREEN}[$ip] Install successful${NC}"
    else
        echo -e "${RED}[$ip] Install failed${NC}"
        adb disconnect "$target" 2>/dev/null
        return 1
    fi

    # Launch the app
    echo -e "${YELLOW}[$ip]${NC} Launching Fishbowl..."
    adb -s "$target" shell am start -n com.strix.fishbowl/.MainActivity 2>/dev/null \
        || adb -s "$target" shell monkey -p com.strix.fishbowl 1 2>/dev/null

    # Disconnect
    adb disconnect "$target" 2>/dev/null
    echo -e "${GREEN}[$ip] Done${NC}"
    return 0
}

# --- Main ---
echo "=== Fishbowl Deployment ==="
echo ""

APK_PATH=$(resolve_apk)
echo -e "${GREEN}APK: $APK_PATH${NC}"

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

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

# --- Summary ---
echo ""
echo "=== Deployment Complete ==="
echo -e "${GREEN}Passed: $passed${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