#!/bin/sh

. /etc/utils/shell-utils.sh
DEBUG=0

KERNEL_VERSION="$(uname -r)"

WIFI_CURR_DRIVER_FILE=/ram/wifi/curr_driver
WIFI_HANDLE_LOCK_FILE=/ram/wifi.lock

wifi_driver=$(cat "$WIFI_CURR_DRIVER_FILE" 2>/dev/null)

log "wifi_driver=$wifi_driver"
if [ -n "$wifi_driver" ]; then
    log "[i] External WIFI dongle active. Aborting embedded WIFI start and initializing external WIFI"
    /etc/init.d/wifi_if_handler.sh start
    exit 0
fi

export LD_LIBRARY_PATH="/usr/local/lib:$LD_LIBRARY_PATH"

(
flock -x 555
log "[+] LOCK /ram/wifi.lock"

log "Initializing embedded WIFI module."

#@1 - driver name 8821, 8822,...
#@2 - device id  0xc822, 0xc821
init_internal_88xxcs()
{
    insmod "/lib/modules/${KERNEL_VERSION}/kernel/drivers/realtek/wifi/${1}cs.ko"
    mmc="/sys/bus/mmc/devices/sdio:0001/sdio:0001:1"

    vendor=$(cat "$mmc/vendor" 2>/dev/null)
    device=$(cat "$mmc/device" 2>/dev/null)

    if  [ "$vendor" != "0x024c" ] || [ "$device" != "${2}" ]; then
        rmmod "${1}cs"
    else
        echo 0 > /sys/module/${1}cs/parameters/rtw_drv_log_level
        echo "success"
    fi
}

init_internal_8723du()
{
    log "[+] Embedded RTL8723DU WIFI module FOUND."
    insmod /lib/modules/${KERNEL_VERSION}/kernel/drivers/realtek/wifi/8723du.ko
    echo 0 > /sys/module/8723du/parameters/rtw_drv_log_level
}

init_internal_8822bu()
{
    log "[+] Embedded RTL8822BU WIFI module FOUND."
    insmod /lib/modules/${KERNEL_VERSION}/kernel/drivers/realtek/wifi/8822bu.ko
    echo 0 > /sys/module/8822bu/parameters/rtw_drv_log_level
}

probe_sdio_wifi()
{
    /usr/bin/wifi_power 1

    get_sdio_wifi MODULE
    case "${MODULE}" in
        sprd)
            insmod /lib/modules/${KERNEL_VERSION}/kernel/drivers/uwe5621/uwe5621_bsp_sdio.ko
            insmod /lib/modules/${KERNEL_VERSION}/kernel/drivers/uwe5621/sprdwl_ng.ko
        ;;
        rtk)
            insmod "/lib/modules/${KERNEL_VERSION}/kernel/drivers/realtek/wifi/8822cs.ko"
            echo 0 > /sys/module/8822cs/parameters/rtw_drv_log_level
        ;;
        rtk_8821)
            insmod "/lib/modules/${KERNEL_VERSION}/kernel/drivers/realtek/wifi/8821cs.ko"
            echo 0 > /sys/module/8821cs/parameters/rtw_drv_log_level
        ;;
    esac
}

case "$(lsusb)" in
    *0bda:d723*)
        init_internal_8723du
    ;;
    *0bda:b82c*)
        init_internal_8822bu
    ;;
    *)
        probe_sdio_wifi
    ;;
esac


# init WIFI only if proper hardware module found
if [ -d /sys/class/net/wlan0 ]; then
    ifconfig wlan0 up
    wpa_supplicant -B -iwlan0 -Dnl80211 -c/etc/wpa_supplicant.conf
    ipc_invoke "/etc/init.d/wifi_start_wa.sh &"
else
    log "[i] Embedded WIFI module not found. WIFI will be disabled until external module inserted"
fi

flock -u 555
log "[+] UNLOCK /ram/wifi.lock"
) 555>> $WIFI_HANDLE_LOCK_FILE
