#!/bin/bash
# DHCP configuration already handled by NetworkManager
# This script exist only for compatibility with SpinTecLinux installations
# dhclient eth0:1

if false
then

UBUNTU=`lsb_release -a 2>/dev/null | grep -qi "Ubuntu" && echo "1"`
UBUNTU_VER=`lsb_release -a 2>/dev/null | grep "Description" | awk '/Ubuntu/ { print $3; }' | cut -f1 -d'.'`
if [ "$UBUNTU" -a  $UBUNTU_VER -ge 18 ]
then
# restore routing safely (no global flush)
  GW=$(ip route show default | awk '/default/ {print $3; exit}')

  if [ -n "$GW" ]; then
    ip route replace default via "$GW"
  fi

# restart DHCP safely without interface lifecycle changes
  logger "Euro3G: trying to update dhcp setting for eth0"
  dhclient -r eth0
  sleep 1
  dhclient -4 -nw eth0

# Extract configured static IP (no execution, only parsing)
STATIC_IP=$(awk '
  $0 ~ /iface eth0 inet static/ {found=1; next}
  found && $1=="address" {print $2; exit}
' /etc/network/interfaces)

  if [ -z "$STATIC_IP" ]; then
    logger "Euro3G: - CRITICAL: no static IP configured for eth0"
    exit 1
  fi

# Ensure static IP is present (idempotent repair)
  if ! ip addr show dev eth0 | grep -q "$STATIC_IP"; then
    logger "Euro3G: Restoring static IP $STATIC_IP on eth0"
    ip addr add "$STATIC_IP/24" dev eth0
  fi
else
  route del default
  route del default
  ifdown eth0:1
  /bin/sh -ec 'ifup --allow=hotplug eth0:1; ifup --allow=auto eth0:1; if ifquery eth0:1 > /dev/null; then ifquery --state eth0:1 >/dev/null ; fi'
fi  
fi # if false

STATIC_IP=$(awk '
  $0 ~ /iface eth0 inet static/ {found=1; next}
  found && $1=="address" {print $2; exit}
' /etc/network/interfaces)
UBUNTU=`lsb_release -a 2>/dev/null | grep -qi "Ubuntu" && echo "1"`
UBUNTU_VER=`lsb_release -a 2>/dev/null | grep "Description" | awk '/Ubuntu/ { print $3; }' | cut -f1 -d'.'`
if [ -n "$STATIC_IP" ]
then
  if [ "$UBUNTU" -a  $UBUNTU_VER -ge 18 ]
  then
    ip addr add "$STATIC_IP/24" dev eth0
  else
    ifconfig eth0 $STATIC_IP up
  fi
fi

route del default
route del default
ifdown eth0:1
/bin/sh -ec 'ifup --allow=hotplug eth0:1; ifup --allow=auto eth0:1; if ifquery eth0:1 > /dev/null; then ifquery --state eth0:1 >/dev/null ; fi'

exit 0
