#!/bin/bash

ACTION=$1
shift || true

do_help() {
    echo "${1} list|scanlist|enable <ssid> [key]|disable" >&2
}

# A single connmanctl call, parsed locally.
#
# The stock version ran "connmanctl services <id>" once per access point just
# to read Interface=wlan0. With 20-40 visible APs that is 20-40 D-Bus round
# trips, executed on the EmulationStation UI thread while the SSID menu is
# being built, which freezes the interface for seconds.
do_list() {
    timeout 5 connmanctl services 2>/dev/null | while IFS= read -r line; do
        case "$line" in
            *wifi_*) : ;;
            *) continue ;;
        esac

        svc=${line##* }
        case "$svc" in
            *_p2p*|*_p2p_*) continue ;;
        esac

        # strip the 4 char status prefix ("*AO " or "    ")
        name=${line:4}
        name=${name% "$svc"}
        # trim trailing whitespace
        name=${name%"${name##*[![:space:]]}"}

        [ -z "$name" ] && continue
        case "$name" in
            *'<hidden>'*) continue ;;
        esac
        printf '%s\n' "$name"
    done
}

do_scanlist() {
    timeout 5 connmanctl scan wifi >/dev/null 2>&1
    do_list
}

# EmulationStation calls "batocera-wifi enable <ssid> <key>" and
# "batocera-wifi disable". The stock script implemented neither, so saving
# WiFi settings showed "WIFI ENABLED" while nothing was configured. Delegate
# to the path that actually writes the ConnMan config, bounded by a timeout so
# a wedged scan can never hang the UI forever.
do_enable() {
    timeout 25 /usr/bin/batocera/batocera-config wifi enable "$1" "$2"
}

do_disable() {
    timeout 10 /usr/bin/batocera/batocera-config wifi disable
}

case "${ACTION}" in
    list)     do_list ;;
    scanlist) do_scanlist ;;
    enable)   do_enable "$@" ;;
    disable)  do_disable ;;
    *)        do_help "${0}" ;;
esac
