#!/bin/bash
#
#  Script to convert old-style pre-CIDR/multihoming network configuration
#  files to new format.
#

if [ $# -ne 1 ]
then
    echo "Usage: gsl_convert_old_netconfig.sh <old>"
    echo " * results on stdout"
    echo " * exit status 0 for success"
    exit 1
fi

# read old settings
source "$1"

# check for already-converted file
case "${NETCONFIG_VERSION}" in
1)
    cat "$1"
    exit 0
esac

to_cidr_notation() {
    ADDRESS="$1"
    NETMASK="$2"

    echo "${ADDRESS}/$(ipcalc -ps "${ADDRESS}" "${NETMASK}" | sed -e 's/^.*=//')"
}

default_address_ip="$(to_cidr_notation "${IPADDR}" "${NETMASK}")"
[ "${default_address_ip}" == "/" ] && default_address_ip=""



# do the static part
cat <<EOF
# Version 1 configuration file
NETCONFIG_VERSION="1"

# Interface settings
device="${DEVICE}"
desc="${DESC}"
enable="${ENABLE}"
onboot="${ONBOOT}"

# Device settings
media="${MEDIA}"
mtu="${MTU}"

# DHCP settings
bootproto="${BOOTPROTO}"
dhcpcd_args=""

# static settings, first address
default_address_ip="${default_address_ip}"
default_address_broadcast="${BROADCAST}"
default_address_args=""
default_route_via="${GATEWAYS}"
default_route_args=""

# static settings, other addresses and routes
EOF

# do the dynamic part (only additional routes)
declare -i i
i=0
while true
do
    route_destn="ROUTE_DESTN${i}"
    ROUTE_DESTN="${!route_destn}"
    [ -z "${ROUTE_DESTN}" ] && break

    route_mask="ROUTE_MASK${i}"
    ROUTE_MASK="${!route_mask}"
    route_gateway="ROUTE_GATEWAY${i}"
    ROUTE_GATEWAY="${!route_gateway}"

    echo "route_type${i}=\"unicast\""
    echo "route_destn${i}=\"$(to_cidr_notation "${ROUTE_DESTN}" "${ROUTE_MASK}")\""
    echo "route_via${i}=\"${ROUTE_GATEWAY}\""
    echo "route_args${i}=\"\""

    ((i++))
done
    
exit 0

# vim: ts=4:sw=4:expandtab
