#!/bin/bash
# create by guangwei.li 2024/04/26. for process ecm driver restart. 
# for mac os sometimes can't get dhcp ip address correctly when usb plug and unplug.
# only for ecm driver.

function check_mac_address() 
{
    local mac_address="$1"
    local valid_mac_regex='^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$'

    if [[ $(grep -E "$valid_mac_regex" <<< "$mac_address") ]]; then
        return 0
    else
        return 1
    fi
}

function restart_ecm_driver()
{
    local udcname
    local script_name
    udcname=`ls -1 /sys/class/udc | head -n 1`
    scriptname=`cat /etc/usb/boot_hsusb_comp`
    if [ $scriptname == "Quectel" ]; then
        rm /sys/kernel/config/usb_gadget/g1/configs/c.1/f10 -rf
        cd /sys/kernel/config/usb_gadget/g1/configs/c.1
        ln -s -f ../../../../usb_gadget/g1/functions/gsi.ecm f10
    fi 
    if [ $scriptname == "9059" ]; then
        rm /sys/kernel/config/usb_gadget/g1/configs/c.2/f0 -rf
        cd /sys/kernel/config/usb_gadget/g1/configs/c.2
        ln -s -f ../../../../usb_gadget/g1/functions/gsi.ecm f0
    fi
    cd /sys/kernel/config/usb_gadget/g1/
    echo $udcname > UDC
    echo "[guangwei.li] restart ecm driver ok." > /dev/kmsg
}

# only effect for ecm net driver.
modelname=`cat /etc/quectel-project-version | grep -i 'Project Name' | cut -d ' ' -f 3`

if [ -d /sys/class/net/ecm0 ] && [ $modelname == "EG120KEA_BA" ];then

   counter_file="/tmp/data/ecm_script_retry.txt"
   if [ ! -f $counter_file ]; then
       echo "0" > $counter_file
       echo "[guangwei.li] $0 script first execute, we skip restart ecm driver." > /dev/kmsg
       exit 0
   fi

   counter=$(cat $counter_file)
   counter=$((counter + 1))
   echo $counter > $counter_file
   
   duration=8
   start_time=$(date +%s)

   while [ 1 ]
   do
       elapsed_time=$(( $(date +%s) - start_time ))

       file="/tmp/data/dnsmasq_host.txt"
       if [ -s "$file" ]; then
           macaddr=`cat /tmp/data/dnsmasq_host.txt | cut -d ' ' -f1`
           ipaddr=`cat /tmp/data/dnsmasq_host.txt | cut -d ' ' -f2`
           host=`cat /tmp/data/dnsmasq_host.txt | cut -d ' ' -f3`
           if check_mac_address "$macaddr"; then
               echo "[guangwei.li] host $host get ecm address $macaddr $ipaddr is success" > /dev/kmsg
               echo "0" > $counter_file
               break;
           fi 
       else
           sleep 1
       fi
   
       if (( elapsed_time >= duration )); then
           if (( counter <= 2 )); then
               echo "[guangwei.li] ecm host can not get address we force restart ecm driver now. retry times $counter" > /dev/kmsg
               restart_ecm_driver
           fi 
           break
       fi
   done
fi
