#  Copyright (c) 2023 Qualcomm Technologies, Inc.
#  All Rights Reserved.
#  Confidential and Proprietary - Qualcomm Technologies, Inc.

# In case of RNDIS when IPPT is enabled, lease entry is given based on hostname
# when ifdown happens on RNDIS lease entry is not getting deleted as QCMAP lib don't
# have info when ifdown happens. Deleting lease entry as part of hotplug event.
# Delete entry upon ifdown on RNDIS only when IPPT is enabled.

# log  $(basename "$0") $LINENO "Log message"
. /etc/data/mbbUtils.sh

if [ $ACTION == "ifdown" ] && [ $INTERFACE == "rndis" ]; then
    ippt_enabled=$(uci -q get qcmap_lan.@profile[0].ippt_enable)
    host_name=$(uci -q get qcmap_lan.@profile[0].ippt_host_name)
    no_of_profile=$(uci -q get qcmap_lan.@no_of_configs[0].no_of_profiles)
    if [ $ippt_enabled -eq 1 ] && [ ! -z $host_name ]; then
        echo "Deleting hostname:$host_name from lease file" >> /dev/kmsg
        log $(basename "$0") "update_dhcp_lease" $LINENO "Deleting hostname:$host_name from lease file"
        sed -i "/$host_name/d" /tmp/data/dhcp.leases.lan
        /etc/init.d/dnsmasq restart
    fi
    # In case of FCD if RNDIS link goes down delete all lease file
    # and restart dnsmasq as older MAC still holding public IP.
    DNSMASQ_HOST_FILE="/tmp/data/dnsmasq_host.txt"
    DHCP_LEASE_FILE="/tmp/data/dhcp.leases"
    dnsmaq_restart_needed=0
    for i in `seq 0 $no_of_profile`; do
        ippt_type=$(uci -q get qcmap_lan.@profile[$i].ippt_device_type)
        ippt_active=$(uci -q get qcmap_lan.@profile[$i].active_ippt)

        if [ $ippt_type == "Any" ] && [ $ippt_active -eq 1 ]; then
            #Get all Mapped VLAN on this profile.
            vlans=$(uci -q get qcmap_lan.@profile[0].vlan_ids)
            log $(basename "$0") "update_dhcp_lease:" $LINENO "Profile:$i list of vlans:$vlans"
            echo "Profile:$i list of vlans:$vlans" >> /dev/kmsg
            for idx in $vlans; do
                dnsmaq_restart_needed=1
                if [ $idx -eq 0 ]; then
                    log $(basename "$0") "update_dhcp_lease:" $LINENO "Deleting ${DHCP_LEASE_FILE}.lan"
                    rm -rf "${DHCP_LEASE_FILE}.lan"
                else
                    log $(basename "$0") "update_dhcp_lease:" $LINENO "Deleting file ${DHCP_LEASE_FILE}.lan$idx"
                    rm -rf "${DHCP_LEASE_FILE}.lan$idx"
                fi
            done
        fi
    done
    if [ $dnsmaq_restart_needed -eq 1 ]; then
         log $(basename "$0") "update_dhcp_lease:" $LINENO "Delete dnsmasq host file and restart dnsmasq"
         echo "Delete dnsmasq host file and restart dnsmasq" >> /dev/kmsg
         rm -rf $DNSMASQ_HOST_FILE
        /etc/init.d/dnsmasq restart
    fi
fi
