#!/usr/bin/env bash
# 
# Copyright 2008-2011 VMware, Inc.  All rights reserved. 
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# 
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
# 
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
# 

# 
# If called as vami_announce_net, announce the network parameters
# If called as vami_config_net, change the network parameters
#

export TEXTDOMAINDIR=/opt/vmware/lib/locale
export TEXTDOMAIN=vami_announce_net

# read in local environment, needed for exec from the blue console UI
. /etc/environment

#
# read in common variables
#
VAMI_SHARE=/opt/vmware/share/vami
. $VAMI_SHARE/vami_common

#
# read in appliance specific parameters
#
VAMI_ETC=/opt/vmware/etc
. $VAMI_ETC/appliance_config

APPLIANCE_TEXT=$VAMI_ETC/isv/textscript

IPV4ENABLEDCMD="$VAMI_SHARE/vami_ipv4support -q"
IPV6ENABLEDCMD="$VAMI_SHARE/vami_ipv6support -q"
VAMI_ANNOUNCE_NET=$VAMI_SHARE/vami_announce_net

MENU_TEXT=`gettext "Type Ctrl-C to go back to the Main Menu\n"`

BLUEBG=`tput setab 4`
BLACKBG=`tput setab 0`
BOLD=`tput bold`
REVERSE=`tput rev`
NORMAL=`tput sgr0`
GREENFG=`tput setaf 2`
WHITEFG=`tput setaf 7`
YELLOWFG=`tput setaf 3`
CLEAR_SCREEN=`tput clear`

TITLE_ON=${REVERSE}${BOLD}
TITLE_OFF=$NORMAL
HEAD_ON=$REVERSE
HEAD_OFF=$NORMAL
DATA_ON=$BOLD
DATA_OFF=$NORMAL

#
# I can't decide whether or not I prefer bold prompts
#
PROMPT_ON=${BOLD}
PROMPT_OFF=${NORMAL}
# PROMPT_ON=
# PROMPT_OFF=

#
# IPv4 and IPv6 regular expressions.
#
ipv4_regex="\(25[0-5]\|2[0-4][0-9]\|[01]\?[0-9][0-9]\?\)\(\.\(25[0-5]\|2[0-4][0-9]\|[01]\?[0-9][0-9]\?\)\)\{3\}"
ipv6_hex="[0-9A-Fa-f]\{1,4\}";
ipv6_last2="\($ipv6_hex:$ipv6_hex\|$ipv4_regex\)";

ipv6_regex="\(\($ipv6_hex:\)\{6\}$ipv6_last2$"\
"\|::\($ipv6_hex:\)\{5\}$ipv6_last2$"\
"\|\($ipv6_hex\)\?::\($ipv6_hex:\)\{4\}$ipv6_last2$"\
"\|\(\($ipv6_hex:\)\{0,1\}$ipv6_hex\)\?::\($ipv6_hex:\)\{3\}$ipv6_last2$"\
"\|\(\($ipv6_hex:\)\{0,2\}$ipv6_hex\)\?::\($ipv6_hex:\)\{2\}$ipv6_last2$"\
"\|\(\($ipv6_hex:\)\{0,3\}$ipv6_hex\)\?::\($ipv6_hex:\)$ipv6_last2$"\
"\|\(\($ipv6_hex:\)\{0,4\}$ipv6_hex\)\?::$ipv6_last2$"\
"\|\(\($ipv6_hex:\)\{0,5\}$ipv6_hex\)\?::$ipv6_hex$"\
"\|\(\($ipv6_hex:\)\{0,6\}$ipv6_hex\)\?::\)$";


ignore_interrupts()
{
    trap "" INT
}

reset_interrupts()
{
    trap - INT TERM
}

catch_interrupts()
{
    trap "cleanup_and_exit 0" TERM
}

normal_exit()
{
    kill $$
}

cleanup_and_exit()
{
    reset_colors
    exit $1
}

#
# center text
#
# $1 == string for color on
# $2 == string for color off
# $3 == string to center
#
center()
{
    col_on="$1"
    col_off="$2"
    text="$3"

    halfcols=$((`stty size | cut -f2 -d' '` / 2))

    nchars=${#text}
    nspaces=$(($halfcols - $nchars / 2))
    while [ $nspaces -gt 0 ]
    do
        echo -e " "\\c
        nspaces=$(($nspaces - 1))
    done
    echo ${col_on}${text}${col_off}
}

center_data()
{
    center ${DATA_ON} "$*" ${DATA_OFF}
}

#
# print a title
#
title()
{
    echo ${TITLE_ON} "$*" ${TITLE_OFF}
}

#
# reset the colors
#
reset_colors()
{
    echo ${NORMAL}
}

ipv4_is_enabled()
{
    $IPV4ENABLEDCMD
    return $?
}

ipv6_is_enabled()
{
    $IPV6ENABLEDCMD
    return $?
}

get_current_global()
{
    export HNAME=`vami_fullhostname`
    export PROXY_SERVER=`vami_proxy_server`
    export PROXY_PORT=`vami_proxy_port`

    export DNS1=`vami_dns | sed -n 's/^nameserver1 \(.*\)/\1/p'`
    export DNS2=`vami_dns | sed -n 's/^nameserver2 \(.*\)/\1/p'`
    export DOMAINNAME=`vami_dns | sed -n 's/^domain \(.*\)/\1/p'`
    export SEARCHPATH=`vami_dns | sed -n 's/^searchpath \(.*\)/\1/p'`

    export USING_DHCP4=False
    export USING_DHCP6=False
    if using_dhcp4
    then
        USING_DHCP4=True
    fi
    if using_dhcp6
    then
        USING_DHCP6=True
    fi
}

#
# initialize all network parameters with current values
#
# $1 == interface
#
get_current_network()
{
    i=$1
    export IP_ADDR=`vami_ip_addr $i`
    export NETMASK=`vami_netmask $i`
    export GATEWAY=`vami_gateway $i`
    export PREFIX=`vami_prefix $i`
    export IP6_ADDR=`vami_ip6_addr $i`
    export AUTOV6_ADDR=`vami_autoip_addr $i`
    export GATEWAYV6=`vami_gateway6 $i`

    get_current_global
}

get_current_ipv6_mode()
{
    if [ "$USING_DHCP6" = "True" ]
    then
        mode=DHCPV6
    elif [ "$IP6_ADDR" != "" ]
    then
        mode=STATICV6
    elif [ "$AUTOV6_ADDR" != "" ]
    then
        mode=AUTOV6
    fi
    echo $mode
}

get_current_mode()
{
    mode=`get_current_ipv6_mode`

    if [ "$USING_DHCP4" = "True" ]
    then
        mode=DHCPV4${mode:++}$mode
    elif [ "$IP_ADDR" != "" ]
    then
        mode=STATICV4${mode:++}$mode
    fi

    echo $mode
}


#
# update the proxy server
#
# $1 == server
# $2 == port
#
set_proxy()
{
    #
    # If we havn't been passed a proxy server, remove any existing
    # proxy config. Otherwise, set it.
    #
    if [ "$1" = "" ]
    then
        vami_set_proxy NONE
    else
        vami_set_proxy $1 $2
    fi
}


#
# set the dns configuration
#
# $1 == domain name
# $2 == search path
# $3 == DNS Server 1
# $4 == DNS Server 2 (or not passed)
#
set_dns()
{
    vami_set_dns ${1:+"-d $1"} ${2:+"-s $2"} "$3" $4
}

#
# determine if we are using dhcp
#
using_dhcp4()
{
    ps -ef | grep -v grep | grep -v '\(dhclient6\)\|\(dhcpcd6\)' | grep '\(dhclient\)\|\(dhcpcd\)' > /dev/null 2>&1
    return $?
}

using_dhcp6()
{
    ps -ef | grep -v grep | grep '\(dhclient6\)\|\(dhcpcd6\)' > /dev/null 2>&1
    return $?
}

dhcp_warn()
{
    stderr
    stderr `gettext "Warning: if any of the interfaces for this VM use DHCP,"`
    stderr `gettext "the Hostname, DNS, and Gateway parameters will be"`
    stderr `gettext "overwritten by information from the DHCP server."`
    stderr
}


#
# validate the IPv4 address
#
# returns 0 if valid (shell syntax says that a 0 return is good)
#
valid_ipv4()
{
    expr "$1" : "$ipv4_regex$" > /dev/null
    return $?
}

#
# validate the IPv6 address
#
# returns 0 if valid (shell syntax says that a 0 return is good)
#
valid_ipv6()
{
    expr "$1" : "$ipv6_regex" > /dev/null
    return $?
}

valid_ipv4_or_ipv6()
{
    if valid_ipv4 $1
    then
        return 0
    elif valid_ipv6 $1
    then
        return 0
    fi
    return 1
}


#
# validate the IPv6 prefix
#
# returns 0 if valid (shell syntax says that a 0 return is good)
#
valid_prefix()
{
    expr "$1" : "[0-9]\+$" > /dev/null
    return $?
}

#
# determines if the mode string contains dhcp
#
# returns 0 if valid (shell syntax says that a 0 return is good)
#
mode_uses_dhcp()
{
    expr "$1" : ".*DHCP" > /dev/null
    return $?
}

#
# Read a string
#
get_string()
{
    read a
    echo "$a"   
}

#
# return a ipv4 format number from the user
#
# $1 == prompt
# $2 == default value
#
get_validated_ipv4()
{
    PROMPT=$1
    DEF=$2
    VALID=FALSE

    while [ $VALID = FALSE ]
    do
        stderr ${PROMPT_ON}${PROMPT} [$DEF]:${PROMPT_OFF} ${DATA_ON}\\c
        response=`get_string`; stderr ${DATA_OFF}\\c

        if [ "$response" = "" ]
        then
            response=$DEF
        fi
        
        if valid_ipv4 $response
        then
            VALID=TRUE
        else
            stderr $response `gettext "is not valid. It needs to be like nnn.nnn.nnn.nnn"`
        fi
    done
    echo $response
}

#
# return a ipv6 format number from the user
#
# $1 == prompt
# $2 == default value
#
get_validated_ipv6()
{
    PROMPT=$1
    DEF=$2
    VALID=FALSE

    while [ $VALID = FALSE ]
    do
        stderr ${PROMPT_ON}${PROMPT} [$DEF]:${PROMPT_OFF} ${DATA_ON}\\c
        response=`get_string`; stderr ${DATA_OFF}\\c

        if [ "$response" = "" ]
        then
            response=$DEF
        fi
        
        if valid_ipv6 $response
        then
            VALID=TRUE
        else
            stderr $response `gettext "is not valid. Not a valid IPv6 address."`
        fi
    done
    echo $response
}

#
# return a ipv6 format number or blank from the user
#
# $1 == prompt
# $2 == default value
#
get_validated_ipv6_or_none()
{
    PROMPT=$1
    DEF=$2
    VALID=FALSE

    while [ $VALID = FALSE ]
    do
        stderr ${PROMPT_ON}${PROMPT} [$DEF]:${PROMPT_OFF} ${DATA_ON}\\c
        response=`get_string`; stderr ${DATA_OFF}\\c

        if [ "$response" = "" ]
        then
            VALID=TRUE
        elif valid_ipv6 $response
        then
            VALID=TRUE
        else
            stderr $response `gettext "is not valid. It needs to be like xx:xx:xx:xx:xx:xx:xx"`
        fi
    done
    echo $response
}

#
# return a ipv6 format number from the user
#
# $1 == prompt
# $2 == default value
#
get_validated_ipv4_or6()
{
    PROMPT=$1
    DEF=$2
    VALID=FALSE
    validerr="nnn.nnn.nnn.nnn"

    if ipv6_is_enabled
    then
        validerr="$validerr OR xx:xx:xx:xx:xx:xx:xx"
    fi

    while [ $VALID = FALSE ]
    do
        stderr ${PROMPT_ON}${PROMPT} [$DEF]:${PROMPT_OFF} ${DATA_ON}\\c
        response=`get_string`; stderr ${DATA_OFF}\\c

        if [ "$response" = "" ]
        then
            response=$DEF
        fi
        
        if valid_ipv6 $response
        then
            VALID=TRUE
        elif valid_ipv4 $response
        then
            VALID=TRUE
        else
            stderr $response `gettext "is not valid. It needs to be like"` $validerr
        fi
    done
    echo $response
}

#
# return a ipv6 prefix from the user
#
# $1 == prompt
# $2 == default value
#
get_validated_prefix()
{
    PROMPT=$1
    DEF=$2
    VALID=FALSE

    while [ $VALID = FALSE ]
    do
        stderr ${PROMPT_ON}${PROMPT} [$DEF]:${PROMPT_OFF} ${DATA_ON}\\c
        response=`get_string`; stderr ${DATA_OFF}\\c

        if [ "$response" = "" ]
        then
            response=$DEF
        fi
        
        if valid_prefix $response
        then
            VALID=TRUE
        else
            stderr "$response" `gettext "is not valid. It needs to be in the range"` "[1-127]"
        fi
    done
    echo $response
}


#
# return a prompted string from the user
#
# $1 == prompt
# $2 == default value
#
get_string_with_prompt()
{
    PROMPT=$1
    DEF=$2

    stderr ${PROMPT_ON}${PROMPT} [$DEF]:${PROMPT_OFF} ${DATA_ON}\\c
    response=`get_string`; stderr ${DATA_OFF}\\c

    if [ "$response" = "" ]
    then
        response=$DEF
    fi

    echo $response
}

#
# return a yes or no from a prompted question
#
# $1 == prompt
# $2 == default value
#
get_yn()
{
    PROMPT=$1
    DEF=$2

    stderr ${HEAD_ON}${PROMPT} y/n [$DEF]:${HEAD_OFF} ${DATA_ON}\\c
    response=`get_string`; stderr ${DATA_OFF}\\c

    if [ "$response" = "" ]
    then
        response=$DEF
    fi

    echo $response
}

#
# print progress
#
# $* == string to print
#
progress()
{
    echo ${HEAD_ON}$*${HEAD_OFF}
}

#
# print a line with a description: followed by data
#
# $1 == description
# $2 == data
#
print_data()
{
    echo -e ${HEAD_ON}${1}:${HEAD_OFF}\\t${DATA_ON}${2}${DATA_OFF}
}

#
# print a non-colored line with a description: followed by data
#
# $1 == description
# $2 == data
#
print_plain_data()
{
    echo -e ${1}:\\t${2}
}

#
# print a non-colored line of data
#
# $1 == data
#
print_plain()
{
    echo -e $@
}

announce()
{
    print_plain
    print_plain "`gettext \"Network Configuration for \"`" "$1"

    if ipv4_is_enabled
    then
        print_plain_data "`gettext \"IPv4 Address\"`" "$IP_ADDR"
        print_plain_data "`gettext \"Netmask\"`" "$NETMASK"
    fi

    if ipv6_is_enabled
    then
        print_plain_data "`gettext \"IPv6 Address\"`" "$IP6_ADDR"
        print_plain_data "`gettext \"Prefix\"`" "\t$PREFIX"
    fi
}

announce_global()
{
    print_plain `gettext "Global Configuration"`

    if ipv4_is_enabled
    then
        print_plain_data "`gettext \"IPv4 Gateway\"`" "$GATEWAY"
    fi

    if ipv6_is_enabled
    then
        print_plain_data "`gettext \"IPv6 Gateway\"`" "$GATEWAYV6"
    fi

    print_plain_data "`gettext 'Hostname'`" "$HNAME"
    print_plain_data "`gettext \"DNS Servers\"`" "${DNS1}${DNS2:+, $DNS2}"
    print_plain_data "`gettext \"Domain Name\"`" "$DOMAINNAME"
    print_plain_data "`gettext \"Search Path\"`" "$SEARCHPATH"    

    if [ "$PROXY_SERVER" = "" -a "$PROXY_PORT" = "" ]
    then
        print_plain_data "`gettext \"Proxy Server\"`" ""
    else
        print_plain_data "`gettext \"Proxy Server\"`" "${PROXY_SERVER}:${PROXY_PORT}"
    fi
}


config_ipv4()
{
    interface=$1

    CORRECT=FALSE

    while [ $CORRECT = FALSE ]
    do
        #
        # offer the default choice of whatever is currently configured
        #
        if [ "$USING_DHCP4" = "True" ]
        then
            def="y"
        else
            def="n"
        fi

        dhcpv4=`get_string_with_prompt "\`gettext 'Use a DHCPv4 Server instead of a static IPv4 address? y/n'\`" $def`

        if [ "$dhcpv4" = "y" ]
        then
            NEW_IP_ADDR=AUTOMATIC
            NEW_NETMASK=AUTOMATIC
            NEW_GATEWAY=AUTOMATIC
            NEW_DNS1=AUTOMATIC
            NEWMODE=DHCPV4${MODE:++}$MODE
        else
            NEW_IP_ADDR=`get_validated_ipv4 "\`gettext 'IPv4 Address'\`" "$IP_ADDR"`
            NEW_NETMASK=`get_validated_ipv4 "\`gettext 'Netmask'\`" "$NETMASK"`

            NEWMODE=STATICV4${MODE:++}$MODE
        fi

        print_data "`gettext 'IPv4 Address'`" "$NEW_IP_ADDR"
        print_data "`gettext 'Netmask'`" "$NEW_NETMASK"

        echo    
        a=`get_string_with_prompt "\`gettext 'Is this correct? y/n'\`" y`

        if [ "$a" = "y" ]
        then
            CORRECT=TRUE
            MODE=$NEWMODE
        fi
        echo
    done
}


config_ipv6()
{
    interface=$1

    CORRECT=FALSE

    while [ $CORRECT = FALSE ]
    do
        #
        # offer the default choice of whatever is currently configured
        #
        if [ "$USING_DHCP6" = "True" ]
        then
            def="y"
        else
            def="n"
        fi

        dhcpv6=`get_string_with_prompt "\`gettext 'Use a DHCPv6 Server instead of a static IPv6 address? y/n'\`" $def`

        if [ "$dhcpv6" = "y" ]
        then
            NEW_IP6_ADDR=AUTOMATIC
            NEW_PREFIX=AUTOMATIC
            NEW_GATEWAYV6=AUTOMATIC
            MODE=DHCPV6
        else
            NEW_IP6_ADDR=`get_validated_ipv6 "\`gettext 'IPv6 Address'\`" "$IP6_ADDR"`
            NEW_PREFIX=`get_validated_prefix "\`gettext 'Prefix'\`" "$PREFIX"`
            MODE=STATICV6
        fi
        print_data "`gettext 'IPv6 Address'`" "$NEW_IP6_ADDR"
        print_data "`gettext 'Prefix'`" "\t$NEW_PREFIX"

        echo    
        a=`get_string_with_prompt "\`gettext 'Is this correct? y/n'\`" y`

        if [ "$a" = "y" ]
        then
            CORRECT=TRUE
        fi
        echo
    done
}

reconfigure_interface()
{
    interface=$1
    mode=$2
    ip=$3
    mask=$4
    gate=$5
    ip6=$6
    prefix=$7
    gate6=$8
    
    progress `gettext Reconfiguring` $interface...

    trap "" INT

    if [ $mode = "DHCPV4" -o $mode = "DHCPV4+DHCPV6" -o $mode = "DHCPV4+AUTOV6" -o $mode = "DHCPV6"  ]
    then
        vami_set_network $interface "$mode"
    elif [ $mode = "AUTOV6" ]
    then
        vami_set_network $interface "$mode"
    elif [ $mode = "STATICV4" -o $mode = "STATICV4+AUTOV6" ]
    then
        vami_set_network $interface "$mode" "$ip" "$mask" "$gate"
    elif [ $mode = "STATICV4+DHCPV6" ]
    then
        vami_set_network $interface "$mode" "$ip" "$mask" "$gate"
    elif [ $mode = "DHCPV4+STATICV6" ]
    then
        vami_set_network $interface "$mode" "$ip6" "$prefix" "$gate6"
    elif [ $mode = "STATICV6" ]
    then
        vami_set_network $interface "$mode" "$ip6" "$prefix" "$gate6"
    else
        vami_set_network $interface "$mode" "$ip" "$mask" "$gate" "$ip6" "$prefix" "$gate6"
    fi

    trap - INT
}



config_interface()
{
    interface=$1
    changed=False

    print_plain "$MENU_TEXT"

    get_current_network $interface

    ip=$IP_ADDR
    mask=$NETMASK
    ip6=$IP6_ADDR
    prefix=$PREFIX

    MODE=
    if ipv6_is_enabled
    then
        yn=`get_string_with_prompt "\`gettext 'Configure an IPv6 address for'\` $interface? y/n" n`

        if [ "$yn" = "y" ]
        then
            config_ipv6 $interface
            changed=True
            ip6=$NEW_IP6_ADDR
            prefix=$NEW_PREFIX
        fi
    fi

    if ipv4_is_enabled
    then
        yn=`get_string_with_prompt "\`gettext 'Configure an IPv4 address for'\` $interface? y/n" n`

        if [ "$yn" = "y" ]
        then
            config_ipv4 $interface
            changed=True
            ip=$NEW_IP_ADDR
            mask=$NEW_NETMASK
        fi
    fi

    if [ "$changed" = "True" ]
    then
        reconfigure_interface $interface "$MODE" "$ip" "$mask" "$GATEWAY" "$ip6" "$prefix" "$GATEWAYV6"
    fi
}

DNS()
{
    dhcp_warn
    print_plain "$MENU_TEXT"

    get_current_global

    if ipv4_is_enabled
    then
        if ipv6_is_enabled
        then
            query1=get_validated_ipv4_or6
            query2=valid_ipv4_or_ipv6
        fi
    fi

    if ipv4_is_enabled
    then
        if ! ipv6_is_enabled
        then
            query1=get_validated_ipv4
            query2=valid_ipv4
        fi
    fi

    if ! ipv4_is_enabled
    then
        if ipv6_is_enabled
        then
            query1=get_validated_ipv6
            query2=valid_ipv6
        fi
    fi

    if ! ipv4_is_enabled
    then
        if ! ipv6_is_enabled
        then
            return
        fi
    fi

    NEW_DNS1=`$query1 "\`gettext 'DNS Server 1'\`" "$DNS1"`
    NEW_DNS2=`get_string_with_prompt "\`gettext 'DNS Server 2 (optional)'\`" "$DNS2"`
    NEW_DOMAINNAME=`get_string_with_prompt "\`gettext 'Domain Name (optional)'\`" "$DOMAINNAME"`
    NEW_SEARCHPATH=`get_string_with_prompt "\`gettext 'Search Path (space separated) (optional)'\`" "$SEARCHPATH"`

    if [ "$NEW_DNS2" != "" ]
    then
        while ! $query2 $NEW_DNS2
        do
            stderr "`gettext 'The address format entered is not valid.'`"
            NEW_DNS2=`get_string_with_prompt "\`gettext 'DNS Server 2 (optional)'\`" "$DNS2"`
        done
    fi
    set_dns "$NEW_DOMAINNAME" "$NEW_SEARCHPATH" $NEW_DNS1 $NEW_DNS2
}

Gateway()
{
    dhcp_warn
    print_plain "$MENU_TEXT"

    declare -a ch

    for i in $interfaces
    do
        ch+=("$i")
    done

    while :
    do
        i=0
        while [ $i -lt ${#ch[*]} ]
        do
            print_plain "$i)\t${ch[$i]}"
            (( i += 1 ))
        done
        wanted=`get_string_with_prompt "\`gettext 'Choose the interface to associate with default gateway'\`" 0`
        if [ $wanted -ge ${#ch[*]} -o $wanted -lt 0 ]
        then
            print_plain "`gettext 'Invalid choice. Please choose a menu number.'`"
            continue
        else
            break
        fi
    done

    interface=${ch[$wanted]}

    print_plain `gettext 'Gateway will be associated with'` $interface

    get_current_network $interface
    MODE=`get_current_mode`

    if ipv4_is_enabled
    then
        NEW_GATEWAY=`get_validated_ipv4 "\`gettext 'IPv4 Default Gateway'\`" "$GATEWAY"`
    fi
    
    if ipv6_is_enabled
    then
        NEW_GATEWAYV6=`get_validated_ipv6_or_none "\`gettext 'IPv6 Default Gateway'\`" "$GATEWAYV6"`
    fi

    #
    # The basic strategy here is to figure out what "MODE" we are in
    # so that vami_set_network can set up the same network that is
    # already in place for this interface, but with a new gateway.
    #
    reconfigure_interface $interface "$MODE" "$IP_ADDR" "$NETMASK" "$NEW_GATEWAY" "$IP6_ADDR" "$PREFIX" "$NEW_GATEWAYV6"
}


Hostname()
{
    dhcp_warn
    print_plain "$MENU_TEXT"

    current=`vami_fullhostname`
    h=`get_string_with_prompt "\`gettext 'New hostname'\`" "$current"`
    vami_set_hostname "$h"
}

Proxy()
{
    print_plain "$MENU_TEXT"

    PROXY_SERVER=`vami_proxy_server`
    PROXY_PORT=`vami_proxy_port`
    NEW_PROXY_SERVER=
    NEW_PROXY_PORT=
    #
    # offer the default choice of whatever is currently configured
    #
    if [ "$PROXY_SERVER" != "" ]
    then
        def="y"
    else
        def="n"
    fi

    a=`get_string_with_prompt "\`gettext 'Is an IPv4 proxy server necessary to reach the Internet? y/n'\`" $def`

    if [ "$a" = "y" ]
    then
        while [ "$NEW_PROXY_SERVER" = "" -o "$NEW_PROXY_PORT" = "" ]
        do
            NEW_PROXY_SERVER=`get_string_with_prompt "\`gettext 'Proxy Server (http:// will be auto prepended)'\`" "$PROXY_SERVER"`
            NEW_PROXY_PORT=`get_string_with_prompt "\`gettext 'Proxy Port'\`" "$PROXY_PORT"`

            if [ "$NEW_PROXY_SERVER" = "" -o "$NEW_PROXY_PORT" = "" ]
            then
                stderr "`gettext 'Proxy Server and Port must both be set.'`"
            fi
        done
    else
        NEW_PROXY_SERVER=""
    fi

    set_proxy "$NEW_PROXY_SERVER" "$NEW_PROXY_PORT"
}

################################
# MAIN PROGRAM START
################################

NAME=`basename $0`
export interfaces=${1:-`vami_interfaces`}

case $NAME in
    vami_announce_net)
        for i in $interfaces
        do
            get_current_network $i
            announce $i
        done
        print_plain ""
        announce_global
        ;;

    vami_config_net)
        catch_interrupts
        declare -a choices
        declare -a operations

        choices+=("`gettext 'Show Current Configuration (scroll with Shift-PgUp/PgDown)'`")
        operations+=("$VAMI_ANNOUNCE_NET")

        choices+=("`gettext 'Exit this program'`")
        operations+=("normal_exit")

        choices+=("`gettext 'Default Gateway'`")
        operations+=("Gateway")

        choices+=("`gettext 'Hostname'`")
        operations+=("Hostname")

        choices+=("`gettext 'DNS'`")
        operations+=("DNS")        

        choices+=("`gettext 'Proxy Server'`")
        operations+=("Proxy")

        for i in $interfaces
        do
            choices+=("`gettext 'IP Address Allocation for'` $i")
            operations+=("config_interface $i")
        done

        ignore_interrupts
        
        while :
        do
            echo
            title "`gettext 'Main Menu'`"
            echo
            i=0
            while [ $i -lt ${#choices[*]} ]
            do
                print_plain "$i)\t${choices[$i]}"
                (( i += 1 ))
            done
            wanted=`get_string_with_prompt "\`gettext 'Enter a menu number'\`" 0`

            lastchoice=`expr ${#choices[*]} - 1`

            case "$wanted" in
            [0-9]*)
                if [ $wanted -gt $lastchoice -o $wanted -lt 0 ]
                then
                    print_plain "`gettext 'Invalid choice. Please choose a menu number from 0 to'` $lastchoice."
                    continue
                fi
                ;;
            *)
                print_plain "`gettext 'Invalid input. Please choose a menu number from 0 to'` $lastchoice."
                continue
                ;;
            esac
            #
            # Run each operation as a subprocess, with SIGINT (Ctrl-C) reset,
            # so Ctrl-C will get us back to the main menu.
            #
            (
                reset_interrupts
                ${operations[$wanted]}
            )
        done
        ;;
    *)
        stderr $0 `gettext 'is an unknown name for this program'`
        cleanup_and_exit 1
        ;;
esac

cleanup_and_exit 0
