#!/bin/sh
#
# Start the rce wifi config....
#


. /etc/rap/vars
. $UTILSDIR/shini

NAME_STG="rce_wifi_cfg"



__shini_parse_error()
{
	case "$2" in
		"")
			;;
		"a")
			;;

		*)
			echo "$NAME_STG: Parse error thrown wrongly on '$1' '$2'" 1>&2
			FAIL=1
			;;
	esac
}

__shini_parsed()
{
        var1=$(printf "INI__%s__%s" $1 $2)
        var2=$(printf "%s" $3)
        export $var1=$var2
}

WPAS_NAME=wpa_supplicant
WPAS_DAEMON=/usr/sbin/$WPAS_NAME
WPAS_PIDFILE=/var/run/$WPAS_NAME.pid
WPAS_LOGFILE=/var/log/$WPAS_NAME.log

HOSTAPD_NAME=hostapd
HOSTAPD_DAEMON=/usr/sbin/$HOSTAPD_NAME
HOSTAPD_PIDFILE=/var/run/$HOSTAPD_NAME.pid

DNSMASQ_NAME=dnsmasq
DNSMASQ_DAEMON=/usr/sbin/$DNSMASQ_NAME
DNSMASQ_PIDFILE=/var/run/$DNSMASQ_NAME.pid

DHCP_NAME=udhcpc
DHCP_DAEMON=/sbin/$DHCP_NAME
DHCP_PIDFILE=/var/run/${DHCP_NAME}-wlan0.pid

WIFI_SCAN_RESULTS=$RAP_PROD_RCE_DIR/log/wifi_scan_results.txt

alias check_wlan="ifconfig wlan0 2> /dev/null"
alias check_wlan_1="ifconfig wlan1 2> /dev/null"
alias check_wpa="wpa_cli ping 2> /dev/null | grep PONG"
alias check_ap_connect="wpa_cli status 2> /dev/null | grep state=COMPLETED"
alias check_hostapd="hostapd_cli status 2> /dev/null | grep state=ENABLED"
alias check_dnsmasq="ps | grep -v grep | grep dnsmasq > /dev/null"
alias check_scan="iw wlan0 scan | grep SSID > $WIFI_SCAN_RESULTS"
alias check_rtl8822cs="lsmod | grep 8822cs 2> /dev/null"

function end_script() {
if [ ${ERROR_FLAG} -ne 0 ]
then
    exit 11
else
    exit
fi
}

function check_in_loop() {
local cnt=1
while [ $cnt -lt $1 ]; do
    echo "check_in_loop processing..."
    case "$2" in
        check_wlan)
        check_wlan
        ;;
        check_hostapd)
        check_hostapd
        ;;
        check_dnsmasq)
        check_dnsmasq
        ;;
        check_wpa)
        check_wpa
        ;;
        check_ap_connect)
        check_ap_connect
        ;;
	    check_scan)
	    check_scan
        ;;
    esac
    if [ $? -eq 0 ];then
        return
    else
        cnt=$((cnt + 1))
        sleep 1
        continue
    fi
done

echo "check_in_loop fail!!"
#ERROR_FLAG=1
#end_script
}

function load_driver() {
if [ $1 = "0" ];then
	echo "removing driver if loaded"
else

	echo "start driver loading..."
	##########check wlan0############################
	echo "checking wlan0..."
	check_in_loop 15 check_wlan
	echo "wlan0 shows up"
fi
}

function wifi_stop_ampak() {

load_driver 0

echo "#########stoping wifi#####################"
#####stop wpa_supplicant hostapd dhcpcd dnsamas##
echo "Stop prv wpa_supplicant first"
wpa_pid=`ps | grep wpa_supplicant | awk '{print $1}' | sed -n "1p"`
echo "wpa_pid: $wpa_pid"
kill $wpa_pid
#sleep 1
echo "Stop prv udhcpcd first"
dhcpcd_pid=`ps | grep dhcpcd | awk '{print $1}' | sed -n "1p"`
echo "dhcpcd_pid: $dhcpcd_pid"
kill $dhcpcd_pid
#sleep 1
hostapd_pid=`ps | grep hostapd | awk '{print $1}' | sed -n "1p"`
echo "hostapd_pid: $hostapd_pid"
kill $hostapd_pid
#sleep 1
ifconfig wlan0 down
ifconfig wlan1 down
#sleep 1
}

function wifi_stop_rtl() {

load_driver 0

echo "#########stoping wifi#####################"
#####stop wpa_supplicant hostapd dhcpcd dnsamas##
echo "Stop prv wpa_supplicant first"
wpa_pid=`ps | grep wpa_supplicant | awk '{print $1}' | sed -n "1p"`
echo "wpa_pid: $wpa_pid"
kill $wpa_pid

echo "Stop prv udhcpcd first"
dhcpcd_pid=`ps | grep dhcpcd | awk '{print $1}' | sed -n "1p"`
echo "dhcpcd_pid: $dhcpcd_pid"
kill $dhcpcd_pid

echo "Stop hostapd first"
hostapd_pid=`ps | grep hostapd | awk '{print $1}' | sed -n "1p"`
echo "hostapd_pid: $hostapd_pid"
kill $hostapd_pid

ifconfig wlan0 down

}

function wifi_stop() {
    echo "wifi_stop enter"
    rtl_module=`lsmod | grep 8822cs`
    if [ "$rtl_module" == 0 ]; then
        wifi_stop_rtl $1
    else
        wifi_stop_ampak $1
    fi
}

function wifi_init()
{
	if [ ! -f ${module_pid_file} ];then
		ifconfig wlan0 up
		ifconfig wlan1 up
		sleep 2
	fi
}


function wifi_nw_start_ampak() {
echo "starting wpa_supplicant..."
ifconfig wlan0 0.0.0.0

if [ -f $RAP_PROD_RCE_DIR/etc/wpa_supplicant/wpa_supplicant.conf ]
then
	WPA_CONF=$RAP_PROD_RCE_DIR/etc/wpa_supplicant/wpa_supplicant.conf
elif [ -f /etc/wpa_supplicant/wpa_supplicant.conf ]
then
	WPA_CONF=/etc/wpa_supplicant/wpa_supplicant.conf
else
	exit 0
fi
echo "ctrl_interface=/var/run/wpa_supplicant"
/sbin/start-stop-daemon -S -m -p $WPAS_PIDFILE -b -x $WPAS_DAEMON -- -Dnl80211 -iwlan0 -c$RAP_PROD_RCE_DIR/etc/wpa_supplicant/wpa_supplicant.conf -f $WPAS_LOGFILE
#check_in_loop 2 check_wpa
#check_in_loop 2 check_ap_connect
echo "start wpa_supplicant successfully!!"

sleep 2

############start dhcp#######################
echo "starting wifi udhcp..."
$DHCP_DAEMON -i wlan0
echo "ap connected!!"
}

function wifi_nw_start_rtl() {
echo "starting wpa_supplicant..."
ifconfig wlan0 0.0.0.0

if [ -f $RAP_PROD_RCE_DIR/etc/wpa_supplicant/wpa_supplicant.conf ]
then
	WPA_CONF=$RAP_PROD_RCE_DIR/etc/wpa_supplicant/wpa_supplicant.conf
elif [ -f /etc/wpa_supplicant/wpa_supplicant.conf ]
then
	WPA_CONF=/etc/wpa_supplicant/wpa_supplicant.conf
else
	exit 0
fi
echo "ctrl_interface=/var/run/wpa_supplicant"
/sbin/start-stop-daemon -S -m -p $WPAS_PIDFILE -b -x $WPAS_DAEMON -- -Dnl80211 -iwlan0 -c$RAP_PROD_RCE_DIR/etc/wpa_supplicant/wpa_supplicant.conf -f $WPAS_LOGFILE
echo "start wpa_supplicant successfully!!"

sleep 2

############start dhcp#######################
echo "starting wifi udhcp..."
$DHCP_DAEMON -i wlan0
echo "ap connected!!"
}


function wifi_ap_start_ampak() {
echo "starting hostapd..."
if [ -f $RAP_PROD_RCE_DIR/etc/hostapd/hostapd.conf ]
then
	HOSTAPD_ARGS=$RAP_PROD_RCE_DIR/etc/hostapd/hostapd.conf
elif [ -f /etc/hostapd.conf ]
then
	HOSTAPD_ARGS=/etc/hostapd.conf
else
	exit 0
fi
#Initial wifi interface configuration
printf "Starting rce wifi network: "
#ifconfig wlan0 up $AP_IP netmask $AP_NM        
#[ $? = 0 ] && echo "OK" || echo "FAIL"       
sysctl -w net.ipv4.ip_forward=1

#ifconfig wlan1 up $AP_IP netmask $AP_NM

#start hostapd                 
$HOSTAPD_DAEMON -B $HOSTAPD_ARGS
printf "Started rce wifi network: "   

echo "ap started!!"
}

function wifi_ap_start_rtl() {
echo "starting hostapd..."
if [ -f $RAP_PROD_RCE_DIR/etc/hostapd/hostapd_rtl.conf ]
then
	HOSTAPD_ARGS=$RAP_PROD_RCE_DIR/etc/hostapd/hostapd_rtl.conf
elif [ -f /etc/hostapd.conf ]
then
	HOSTAPD_ARGS=/etc/hostapd.conf
else
	exit 0
fi
#Initial wifi interface configuration
printf "Starting rce wifi network: "
sysctl -w net.ipv4.ip_forward=1

#start hostapd
echo "hostapd conf - $HOSTAPD_ARGS" 
$HOSTAPD_DAEMON -B $HOSTAPD_ARGS
printf "Started rce wifi network: "   

echo "ap started!!"
}


#################wifi start by mode in ini########################
function wifi_start_ampak() {
echo "wifi_start_ampak ENTER" 
if [[ $# -eq 0 ]]; then
printf "skip restart\n"
elif [ "$1" = "restart" ]; then
wifi_stop_ampak
fi

#WLAN1 config STPLUS ST+
#Configure WLAN1 and WLAN0 interfaces
ifconfig wlan0 up #$NW_IP netmask $AP_NM
[ $? = 0 ] && echo "WLAN0 OK" || echo "WLAN0 FAIL"
#sleep 1 #sleep here for updating MAC address
iw phy phy0 interface add wlan1 type managed
ifconfig wlan1 up $AP_IP netmask $AP_NM
#sleep 1 #sleep here for updating MAC address
#Update ACS channel for 5 GHz band.
#/userdata/rce/utils/wifi_acs_select
#STPLUS add wifi_regen_conf
wifi_regen_conf_ampak

shini_parse_section $RAP_USR_INI_FILE setting
mode=$INI__setting__wifi_mode

if [ "${mode}" = "ap" ]; then
	wifi_ap_start_ampak
    	echo "ap is started!!"
elif [ "${mode}" = "nw" ]; then
	wifi_nw_start_ampak
	#ping_test wlan0
elif [ "${mode}" = "apnw" ]; then
#	wifi_nw_start
#	wifi_ap_start
	echo "AP+NW"
else
	echo "invalid mode!"
	#end_script
fi

echo "wifi_start EXIT" 
}

#################wifi start by mode in ini########################
function wifi_start_rtl() {
echo "wifi_start_rtl ENTER" 
#remove the rtl driver
rmmod /lib/modules/4.4.167+/kernel/drivers/net/wireless/rockchip_wlan/rtl8822cs/8822cs.ko8822cs.ko
sleep 1
#add back the rtl driver with vht enable to support higher bandwidth for 5Ghz channels
insmod /lib/modules/4.4.167+/kernel/drivers/net/wireless/rockchip_wlan/rtl8822cs/8822cs.ko rtw_vht_enable=2
sleep 1

if [[ $# -eq 0 ]]; then
printf "skip restart\n"
elif [ "$1" = "restart" ]; then
wifi_stop_rtl
fi

iw wlan0 set type __ap
ifconfig wlan0 up $AP_IP netmask $AP_NM
[ $? = 0 ] && echo "WLAN0 OK" || echo "WLAN0 FAIL"
wifi_regen_conf_rtl

shini_parse_section $RAP_USR_INI_FILE setting
mode=$INI__setting__wifi_mode

if [ "${mode}" = "ap" ]; then
	wifi_ap_start_rtl
    	echo "ap is started!!"
elif [ "${mode}" = "nw" ]; then
	wifi_nw_start_rtl
elif [ "${mode}" = "apnw" ]; then
	echo "AP+NW"
else
	echo "invalid mode!"
fi

echo "wifi_start_rtl EXIT" 
}

#################wifi start by mode in ini########################
function wifi_start()
{
    echo "wifi_start enter"
    check_rtl8822cs
    if [ "$?" == 0 ]; then
        wifi_start_rtl $1
    else
        wifi_start_ampak $1
    fi
}



#################wifi regenerate conf files by mode ini########################
function wifi_regen_conf_ampak() {
echo "wifi_regen_conf_ampak ENTER" 
shini_parse_section $RAP_USR_INI_FILE setting
country_code=$INI__setting__country_code
product_type=$INI__setting__product_type
mode=$INI__setting__wifi_mode
shini_parse_section $RAP_USR_INI_FILE wifi_mode_$mode
if [ "${mode}" = "ap" ]; then
macaddr=`cat /sys/class/net/wlan1/address | sed 's/://g' | tr [a-z] [A-Z]`
ssid=$INI__wifi_mode_ap__ssid"_"$macaddr
hw_mode=$INI__wifi_mode_ap__hwmode
channel=$INI__wifi_mode_ap__channel
passphrase=$INI__wifi_mode_ap__passphrase

#STPLUS Update channel based on ACS for 5 GHz
if [ $hw_mode = "a" ]; then
channel=$(/userdata/rce/utils/wifi_acs_select)
fi

echo !! channel $channel

cat <<EOF > $RAP_PROD_RCE_DIR/etc/hostapd/hostapd.conf
interface=wlan1
driver=nl80211
ssid=$ssid
hw_mode=$hw_mode
channel=$channel
country_code=$country_code
ignore_broadcast_ssid=0
auth_algs=3
macaddr_acl=0

wpa=3
wpa_key_mgmt= WPA-PSK WPA-PSK-SHA256
wpa_pairwise=CCMP
rsn_pairwise=CCMP
wpa_passphrase=$passphrase
ieee80211ac=1
ieee80211n=1
wmm_enabled=1

EOF
sync
echo "hostapd generated!!"
elif [ "${mode}" = "nw" ]; then
ssid=$INI__wifi_mode_nw__ssid
password=$INI__wifi_mode_nw__password
cat <<EOF > $RAP_PROD_RCE_DIR/etc/wpa_supplicant/wpa_supplicant.conf
ctrl_interface=/var/run/wpa_supplicant
ap_scan=1

network={
	ssid="$ssid"
	psk="$password"
	key_mgmt=WPA-PSK
}
EOF
sync
echo "wpa_supplicant generated!!"
else
echo "invalid mode!"
#end_script
fi

echo "wifi_regen_conf_ampak EXIT" 
}



#################wifi regenerate conf files by mode ini########################
function wifi_regen_conf_rtl() {
echo "wifi_regen_conf_rtl ENTER" 
shini_parse_section $RAP_USR_INI_FILE setting
country_code=$INI__setting__country_code
product_type=$INI__setting__product_type
mode=$INI__setting__wifi_mode
shini_parse_section $RAP_USR_INI_FILE wifi_mode_$mode
if [ "${mode}" = "ap" ]; then
macaddr=`cat /sys/class/net/wlan0/address | sed 's/://g' | tr [a-z] [A-Z]`
ssid=$INI__wifi_mode_ap__ssid"_"$macaddr
hw_mode=$INI__wifi_mode_ap__hwmode
channel=$INI__wifi_mode_ap__channel
passphrase=$INI__wifi_mode_ap__passphrase

#STPLUS Update channel based on ACS for 5 GHz
if [ $hw_mode = "a" ]; then
#channel=$(/userdata/rce/utils/wifi_acs_select)
echo "No auto channel selection for rtl"
fi

echo !! channel $channel

cat <<EOF > $RAP_PROD_RCE_DIR/etc/hostapd/hostapd_rtl.conf
interface=wlan0
driver=nl80211
ssid=$ssid
hw_mode=$hw_mode
channel=$channel
country_code=$country_code
ignore_broadcast_ssid=0
auth_algs=3
macaddr_acl=0

wpa=3
wpa_key_mgmt= WPA-PSK WPA-PSK-SHA256
wpa_pairwise=CCMP
rsn_pairwise=CCMP
wpa_passphrase=$passphrase
beacon_int=100
ieee80211ac=1
ieee80211n=1
ht_capab=[SHORT-GI-20][SHORT-GI-40][HT40+][HT40-]
wmm_enabled=1

EOF
sync
echo "hostapd generated!!"
elif [ "${mode}" = "nw" ]; then
ssid=$INI__wifi_mode_nw__ssid
password=$INI__wifi_mode_nw__password
cat <<EOF > $RAP_PROD_RCE_DIR/etc/wpa_supplicant/wpa_supplicant.conf
ctrl_interface=/var/run/wpa_supplicant
ap_scan=1

network={
	ssid="$ssid"
	psk="$password"
	key_mgmt=WPA-PSK
}
EOF
sync
echo "wpa_supplicant generated!!"
else
echo "invalid mode!"
#end_script
fi

echo "wifi_regen_conf_rtl EXIT" 
}
