#!/bin/bash
# Steven Shiau <steven@nchc.org.tw>
# License: GPL
# Description: To get the IP address lists from dhcpd.conf

# Loading setting.
# Load DRBL setting and functions
DRBL_SCRIPT_PATH="${DRBL_SCRIPT_PATH:-/opt/drbl/}"

. $DRBL_SCRIPT_PATH/sbin/drbl-conf-functions

IPLIST="$(mktemp /tmp/iplist.XXXXXX)"
hn_ip_mac="$(mktemp /tmp/hn_ip_mac.XXXXXX)"
ip_range="$(mktemp /tmp/ip_range.XXXXXX)"

# Settings
sort_output="yes"

# Parse command-line options
while [ $# -gt 0 ]; do
  case "$1" in
    -w|--without-sorting)
            shift; sort_output="no"
            ;;
    -v|--verbose)
		shift; VERBOSE="on"
                ;;
    -*)     echo "${0}: ${1}: invalid option" >&2
            usage >& 2
            exit 2 ;;
    *)      break ;;
  esac
done

# (1) for MAC address part
parse_dhcpd_conf $hn_ip_mac
grep "^[[:space:]]*[^#]" $hn_ip_mac | awk -F" " '{print $2}' | cat > $IPLIST

# (2) For range part
grep -iE "^[[:space:]]*range.*;" $DHCPDCONF_DIR/dhcpd.conf | tr -d ";" | awk -F" " '{print $2 " " $3}' > $ip_range
(cat $ip_range; echo ) | # make sure there is a LF at the end
while read range_start range_end; do
  [ -z "$range_start" ] && break
  ip_prefix=$(echo $range_start |cut -d"." -f1-3)
  start_ip=$(echo $range_start |cut -d"." -f4)
  end_ip=$(echo $range_end |cut -d"." -f4)
  ip=$start_ip
  while [ $ip -le $end_ip ]; do
    echo "${ip_prefix}.${ip}" >> $IPLIST
    ip=$((ip+1))
  done
done
#
case "$sort_output" in
  yes) cat $IPLIST | sort | uniq ;;
  no) cat $IPLIST ;;
esac

# clean
[ -f "$IPLIST" ] && rm -f $IPLIST
[ -f "$hn_ip_mac" ] && rm -f $hn_ip_mac
[ -f "$ip_range" ] && rm -f $ip_range

exit 0
