#!/bin/sh
#
# SPDX-License-Identifier: GPL-2.0-or-later
#
# SPDX-FileCopyrightText: 2019-2022 KUNBUS GmbH

interface="$1"

# The RevPi Core is the only product with a disconnected ks8851 interrupt pin.
# The RevPi Connect is not affected.  This is identifiable by the "interrupts"
# property in the DeviceTree:  A value of 0x80000000 means IRQ_NOTCONNECTED.
# (See include/linux/interrupt.h in the kernel source tree.)
# The interrupt must therefore be polled, which occupies about 10% of one CPU
# core of a Compute Module 3. That's a waste of resources if no gateway is
# attached.
irq="$(/usr/bin/od --endian=big -A n -t x4 "/sys/class/net/$interface/device/of_node/interrupts" 2>/dev/null)"
if [ "$irq" != " 80000000" ] ; then
	exit
fi

# It takes a few seconds for the carrier to come up.
ip link set dev "$interface" up
/bin/sleep 5
carrier="$(cat "/sys/class/net/$interface/carrier" 2>/dev/null)"
if [ "$carrier" = 0 ] ; then
	/sbin/dhcpcd --exit "$interface"
	ip link set dev "$interface" down
fi
