#!/bin/sh

init_udhcpd_rtk() {
    local P2PINTF=$1
    PID=$(pidof udhcpd)
    if [ ! $PID ]; then
        echo "=== Wifi: starting udhcpd"
        ADDR=172.29.243.225
        NETMASK=255.255.255.224
        if [ -f /media/ext1:/p2p-ip-config ]; then
            ADDR=$(cat /media/ext1\:/p2p-ip-config | grep addr | sed 's/addr=\(.*\)/\1/')             
            NETMASK=$(cat /media/ext1\:/p2p-ip-config | grep netmask | sed 's/netmask=\(.*\)/\1/')
        fi
        ifconfig $P2PINTF $ADDR netmask $NETMASK
        [ -f /nvram/udhcpd-p2p.leases ] && cp /nvram/udhcpd-p2p.leases /tmp/udhcpd-p2p.leases
        UDHCPD_CONF=/lib/wlan/realtek/udhcpd-p2p.conf
        [ -f /nvram/udhcpd-p2p.conf ] && UDHCPD_CONF=/nvram/udhcpd-p2p.conf
        cp $UDHCPD_CONF /tmp/udhcpd-p2p.conf
        echo "interface $P2PINTF" >> /tmp/udhcpd-p2p.conf
        udhcpd /tmp/udhcpd-p2p.conf
        PID=$(pidof udhcpd)
        if [ ! $PID ]; then
            echo "Wifi: udhcpd did not start !!!"
            return 2
        fi
    fi
    return 0
}

init_udhcpd_bcm() {    
    local WLDIR=
    local P2PINTF=$1

    [ -f /tmp/wlan-driver ] && WLDIR=/lib/wlan/`cat /tmp/wlan-driver`

    # BCM scripts need to be executed from /lib/wlan/<driver>
    cd $WLDIR
    ./p2papp_connected.sh standalone_go $P2PINTF
    return 0;
}

init_udhcpd() {
    # Log an error if driver description is missing. 
    # Script will continue and default to Broadcom
    [ ! -f /tmp/wlan-driver ] && echo "Error: missing file /tmp/wlan-driver"

    if grep -q realtek /tmp/wlan-driver; then
        init_udhcpd_rtk $1
    else
        init_udhcpd_bcm $1 
    fi
}
