#!/bin/sh
set -e

# Function to check if the interface is using DHCP
is_dhcp_enabled() {
    # Check if the interface is set to DHCP in /etc/network/interfaces or its includes
    if grep -qE "iface[[:space:]]+$1[[:space:]]+inet[[:space:]]+dhcp" /etc/network/interfaces /etc/network/interfaces.d/* 2>/dev/null; then
        return 0  # DHCP enabled
    else
        return 1  # Not using DHCP
    fi
}

case "$2" in
up)
        /sbin/ifup $1
        if is_dhcp_enabled "$1"; then
            /sbin/dhclient "$1"
        fi
        ;;
down)
        if is_dhcp_enabled "$1"; then
            /sbin/dhclient -r "$1"
        fi
        /sbin/ifdown "$1"
        ;;
esac
