#!/bin/bash

ipvalid() {
  local ip=${1:-1.2.3.4}
  local IFS=.
  local -a a=($ip)
  [[ $ip =~ ^[0-9]+(\.[0-9]+){3}$ ]] || return 1
  for quad in {0..3}; do
    [[ "${a[$quad]}" -gt 255 ]] && return 1
  done
  return 0
}

DHCPMODE=0

while getopts a:s:g:d:m:p option
do
  case "${option}" in
    a) IPADDRESS=${OPTARG};;
    s) SUBNET=${OPTARG};;
    g) GATEWAY=${OPTARG};;
    d) DNSSERVER=${OPTARG};;
    m) MACADDRESS=${OPTARG};;
    p) DHCPMODE=1;;
  esac
done

IFACENAME="eth0"

echo "Interface       = ${IFACENAME}"
echo "IP address      = ${IPADDRESS}"
echo "Subnet          = ${SUBNET}"
echo "Gateway         = ${GATEWAY}"
echo "DNS server      = ${DNSSERVER}"
echo "MAC address     = ${MACADDRESS}"
echo "DHCP mode flag  = ${DHCPMODE}"

if [[ $DHCPMODE -eq 1 || $IPADDRESS == "0.0.0.0" ]]; then
  echo "Setting to dynamic (DHCP)"
  ifconfig ${IFACENAME} down
  dhclient ${IFACENAME}
  echo "DHCP configuration applied; network settings will be provided by the DHCP server."
else
  if ipvalid "$IPADDRESS" && ipvalid "$SUBNET" && ipvalid "$GATEWAY" && ipvalid "$DNSSERVER"; then
    echo "Setting up static IP"
    ifconfig ${IFACENAME} $IPADDRESS netmask $SUBNET up
    sudo route del default
    sudo route add default gw $GATEWAY ${IFACENAME}
    echo "nameserver $DNSSERVER" > /etc/resolv.conf
    echo "Static IP address set up"
  else
    echo "Invalid network configuration detected. Shutting down interface."
    ifconfig ${IFACENAME} down
  fi
fi

ifconfig ${IFACENAME} up

echo "Change IP address complete"
