#!/bin/sh
#
# Script written by: Zack Winkles <winkie@linuxfromscratch.org>
# Actual content written by: Seth W. Klein <sk@sethwklein.net>
#

# Just in case.
umask 022

# Required gear.
if [ ! -f /usr/bin/http-get ]; then
	echo "Error: http-get script from lfs-utils package is required."
	exit 1
fi

cd /var/tmp

http-get http://www.iana.org/assignments/protocol-numbers
echo -n "Creating new /etc/protocols file..."
cp -f /etc/protocols /etc/protocols.orig
echo "# See protocols(5) for more information." > /etc/protocols
cat protocol-numbers | tr -d '\r' | awk --re-interval '
  match($0, /^[[:blank:]]+([[:digit:]]+)[[:blank:]]{1,5}([^[:blank:]]+)(.*)/, \
	field) {
    sub(/^[[:blank:]]*/, "", field[3])
    printf "%-16s%-5s%-16s# %s\n", \
	  tolower(field[2]), field[1], field[2], field[3]
    next
  }
  { print "# ", $0 }
' >> /etc/protocols
rm -f /var/tmp/protocol-numbers
echo " done."

http-get http://www.iana.org/assignments/port-numbers
echo -n "Creating new /etc/services file..."
cp -f /etc/services /etc/services.orig
echo "# See services(5) for more information." > /etc/services
cat port-numbers | tr -d '\r' | awk '
  BEGIN {
    aliases["nicname"] = "whois"
  }
  match($0,
	/(^[^[:blank:]]+)([[:blank:]]+[[:digit:]]+\/[^[:blank:]]+)(.*)/,
	field) {
    sub(/^[[:blank:]]+/, "&# ", field[3])
    printf "\"%s\"\n", field[1] > "/dev/stderr"
    printf "%s%s%s%s\n", field[1], field[2],
	    (field[1] in aliases) ? " " aliases[field[1]] : "", field[3]
    next
  }
  !/^#/ { if (!sub(/^ /, "#")) { sub(/^/, "# ") } }
  {
    print $0
  }
' >> /etc/services 2>/dev/null
rm -f /var/tmp/port-numbers
echo " done."

