#!/usr/bin/env bash
# android_emu_geo_fix — Fake GPS location on Android emulator via emu geo fix.
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=adb_wsl.sh
source "$SCRIPT_DIR/adb_wsl.sh"

android_emu_geo_fix() {
    local serial lon lat alt

    adb_pick_serial "$@" || exit 3
    local serial="$ADB_PICK_SERIAL"
    set -- "${ADB_PICK_REST[@]}"

    lon="${1:?android_emu_geo_fix: longitude required}"
    lat="${2:?android_emu_geo_fix: latitude required}"
    alt="${3:-}"

    # geo fix only works on emulators, not physical devices
    if [[ "$serial" != emulator-* ]]; then
        echo "android_emu_geo_fix: geo fix only works on emulators (got '$serial')" >&2
        return 1
    fi

    adb_s "$serial" emu geo fix "$lon" "$lat" ${alt:+"$alt"}

    if [[ -n "$alt" ]]; then
        echo "GPS set: $lon, $lat (alt=$alt) on $serial"
    else
        echo "GPS set: $lon, $lat on $serial"
    fi
}

if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
    android_emu_geo_fix "$@"
fi
