#!/bin/sh
# Minimal udhcpc script: apply IP and default route when lease is obtained.
# udhcpc sets: $1=bound|renew|deconfig, $ip, $subnet (dotted), $router, $dns, $interface

mask2cidr() {
  # Convert dotted subnet (e.g. 255.255.255.0) to CIDR prefix (e.g. 24)
  _bits=0
  for _octet in $(echo "$1" | cut -d. -f1) $(echo "$1" | cut -d. -f2) $(echo "$1" | cut -d. -f3) $(echo "$1" | cut -d. -f4); do
    case "$_octet" in
      255) _bits=$((_bits+8)) ;; 254) _bits=$((_bits+7)) ;; 252) _bits=$((_bits+6)) ;;
      248) _bits=$((_bits+5)) ;; 240) _bits=$((_bits+4)) ;; 224) _bits=$((_bits+3)) ;;
      192) _bits=$((_bits+2)) ;; 128) _bits=$((_bits+1)) ;; 0) ;;
    esac
  done
  echo "$_bits"
}

case "$1" in
  deconfig)
    ip addr flush dev "$interface" 2>/dev/null
    ;;
  bound|renew)
    CIDR=$(mask2cidr "${subnet:-255.255.255.0}")
    ip addr flush dev "$interface" 2>/dev/null
    ip addr add "$ip/$CIDR" dev "$interface"
    if [ -n "$router" ]; then
      for r in $router; do
        ip route add default via "$r" dev "$interface" 2>/dev/null
      done
    fi
    if [ -n "$dns" ]; then
      : > /etc/resolv.conf
      for d in $dns; do
        echo "nameserver $d" >> /etc/resolv.conf
      done
    fi
    ;;
esac
