#!/bin/sh

case "$(board_name)" in
rockchip,rk3568-photonicat)
    ;;
ariaboard,photonicat2)
    NEED_FIX_USB_PATH="1"
    ;;
esac

if [ ! -f "/etc/pcat-wlan-init-completed" ]; then
    exit 0
fi

if [ "${ACTION}" = "add" ]; then
    IGNORE_ACTION="0"

    if [ x"${NEED_FIX_USB_PATH}" = x"1" ]; then
        USB_DEV_DETECTED="0"
        USB_DEV=$(find /sys/devices/platform/soc/23000000.usb -name "xhci-hcd.*.auto" | head -1)
        USB_BASENAME="$(basename ${USB_DEV})"
        ADDED_DEV=$DEVPATH
        if [[ "${ADDED_DEV}" == "*platform/soc/23000000.usb/xhci-hcd.*" ]]; then
            IGNORE_ACTION="1"
        fi

        if [ "${USB_BASENAME}" != x"" ]; then
            WLAN_CONFIG_CHANGED="0"
            while true; do
                USB_WLAN_DUP="0"
                i="0"
                while true; do
                    RADIO_IFACE_SECTION="$(uci show wireless.@wifi-iface[$i] | head -n1 | cut -f1 -d=)"
                    RADIO_DEV="$(uci -q get ${RADIO_IFACE_SECTION}.device)"
                    if [ x"${RADIO_DEV}" = x"" ]; then
                        break
                    fi

                    BUS="$(uci -q get wireless.${RADIO_DEV}.path)"

                    if [[ "${BUS}" == "*platform/soc/23000000.usb/xhci-hcd.*" ]]; then
                        USB_WLAN_DUP="$(expr ${USB_WLAN_DUP} + 1)"

                        if [ "${USB_WLAN_DUP}" -le 1 ]; then
                            if [ -d "/sys/devices/${BUS}" ]; then
                                USB_DEV_DETECTED="1"
                            else
                                WIFI_DEVICE=$(echo ${BUS} | sed "s/xhci-hcd.*.auto/${USB_BASENAME}/g")

                                if [ x"${WIFI_DEVICE}" != x"" -a -d "/sys/devices/${WIFI_DEVICE}" ]; then
                                    uci set wireless.${RADIO_DEV}.path="${WIFI_DEVICE}"
                                    uci commit wireless
                                    USB_DEV_DETECTED="1"
                                    WLAN_CONFIG_CHANGED="1"
                                fi
                            fi
                        else
                            uci delete wireless.${RADIO_DEV}
                            uci delete ${RADIO_IFACE_SECTION}
                            uci commit wireless
                            WLAN_CONFIG_CHANGED="1"
                            break
                        fi
                    fi

                    i="$(expr $i + 1)"
                done

                if [ "${USB_WLAN_DUP}" -le 1 ]; then
                    break
                fi
            done
        fi


        if [ x"${USB_DEV_DETECTED}" = x"1" ]; then
            wifi
        fi
    fi

    usbmode -s && sleep 5
    if [ x"${IGNORE_ACTION}" = x"0" ]; then
        [ -n "$(cat /proc/net/wireless | grep wlan)" ] && wifi config && wifi
    fi
fi
