#!/system/bin/sh
# Copyright (C) 2010 by Cambridge Silicon Radio Ltd.
# /system/bin/unififw
# This is run from the driver via kerneld when a UniFi card
# is inserted.
#
# Usage:  unififw [instance] [mode]
#    [instance]     optional instance number of card. "0" for first card,
#                   "1" for second card.
#    [init_mode]    operation mode, "2" for userspace helper

# Find files for:
#   ufmib.dat     - standard MIB for the h/w
#   mac.txt       - MAC address (in text format)

instance="$1"
init_mode="$2"

fwpath=/system/etc/firmware/unifi-sdio-$instance
dev=/dev/unifi$instance

# Fallback to the broadcast MAC addr, which UniFi takes to mean "use the
# MAC address from MIB", typically read from EEPROM
macaddr="FF:FF:FF:FF:FF:FF"
if /system/bin/ls $fwpath/mac.txt; then
    macaddr=$(/system/bin/cat $fwpath/mac.txt)
fi

case "$init_mode" in
        2)
                mibfileparam=""
                if /system/bin/ls $fwpath/ufmib.dat; then
                        mibfileparam="--wifi-mib $fwpath/ufmib.dat"
                fi

                /system/bin/logwrapper /system/bin/unifi_helper --wifi-char-device $dev --wifi-on --wifi-restart-on-error --wifi-exit-on-error --wifi-exit-on-unplug --wifi-address $macaddr $mibfileparam &

                helper_pid=$!
                /system/bin/setprop wlan.driver.helper_pid $helper_pid
                wait $helper_pid
                /system/bin/setprop wlan.driver.helper_pid 0
                /system/bin/setprop wlan.driver.status "failed"
                /system/bin/rmmod unifi_sdio
                exit 0
esac

######################################################
# unifi_manager mode

# Wait for device nodes. When we have no firmware, sometimes when we
# run unifi_manager the device nodes are not there yet, and it fails.
sleep 0.25

# Get MIB(s) and start the driver.
mibfile=""
if /system/bin/ls $fwpath/ufmib.dat; then
    mibfile="$fwpath/ufmib.dat"
fi

/system/bin/unifi_manager -d /dev/unifi$instance -s $macaddr -b $init_mode $mibfile &
helper_pid=$!
/system/bin/setprop wlan.driver.helper_pid $helper_pid
# FIXME TBD
/system/bin/sleep 4
/system/bin/setprop wlan.driver.status "ok"
wait $helper_pid
/system/bin/setprop wlan.driver.helper_pid 0
/system/bin/setprop wlan.driver.status "failed"
/system/bin/rmmod unifi_sdio
exit 0

