#!/bin/bash
# **** License ****
# Version: VPL 1.0
#
# The contents of this file are subject to the Vyatta Public License
# Version 1.0 ("License"); you may not use this file except in
# compliance with the License. You may obtain a copy of the License at
# http://www.vyatta.com/vpl
#
# Software distributed under the License is distributed on an "AS IS"
# basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
# the License for the specific language governing rights and limitations
# under the License.
#
# This code was originally developed by Vyatta, Inc.
# Portions created by Vyatta are Copyright (C) 2007 Vyatta, Inc.
# All Rights Reserved.
#
# Author:	Tom Grennan <tgrennan@vyatta.com>
# Description:	Vyatta Router system setup
#		this is an indirect init sub-script executed by ofr.init
#
# **** End License ****

ACTION=$1

source /etc/default/vyatta

: ${vyatta_prefix:=/opt/vyatta}
: ${vyatta_bindir:=${vyatta_prefix}/bin}
: ${vyatta_sbindir:=${vyatta_prefix}/sbin}
: ${vyatta_sysconfdir:=${vyatta_prefix}/etc}

[[ $PATH == *${vyatta_bindir}* ]] || PATH+=:${vyatta_bindir}
[[ $PATH == *${vyatta_sbindir}* ]] || PATH+=:${vyatta_sbindir}

export PATH

. /lib/lsb/init-functions

IPROUTE2IP=ip
INIT_PID=$$

## BOOTFILE is provided by ofr.init
: ${BOOTFILE:=$prefix/etc/config/config.boot}

declare -a cfg_eth_hwid
declare -a sys_eth_mac=( `cat /sys/class/net/eth*/address` )

# load hwid array from config file as follows
# interface {
# ...
#     ethernet eth# {
#     ...
#	 hw-id: XX:XX:XX:XX:XX:XX
#     ...
#     }
# }
#
# cfg_eth_hwid[#]=xx:xx:xx:xx:xx:xx

load_cfg_eth_hwid ()
{
    eval $( sed -n '
    /^interfaces {/,/^}/ {
	/^ *ethernet eth[0-9]* {/,/^    $/ {
	    /^ *ethernet/ {
		s/.* eth\([0-9]\+\) {$/cfg_eth_hwid[\1]=/
# hold interface name
		h
	    }
	    /^.*hw-id:/ {
# translate field name
		s/.*hw-id: *//
# tolower hex mac address
		y/ABCDEF/abcdef/
# exchange hold and pattern space
		x
# concatenate hold and pattern
		G
		s/\n//p
	    }
	}
    }' $BOOTFILE )
}

have_cfg_eth_hwid ()
{
    local mac=$1

    for hwid in ${cfg_eth_hwid[@]} ; do
	[ $hwid == $mac ] && return 0
    done
    false
}

have_sys_eth_mac ()
{
    local hwid=$1

    for mac in ${sys_eth_mac[@]} ; do
	[ $hwid == $mac ] && return 0
    done
    false
}

# update cfg table with results from system mac detection
# first remove cfg itfs that are no longer in sys table
# if sys mac is already in cfg table, use cfg itf assignment;
# if sys mac isnot in cfg table but given index has hwid of
# another sys itf, add to cfg table in first available slot
# otherwise, [re-]assign cfg eth hwid with sys mac

update_cfg_eth_hwid ()
{
    local -i i

    for i in ${!cfg_eth_hwid[@]} ; do
	if ! have_sys_eth_mac ${cfg_eth_hwid[$i]} ; then
	    unset cfg_eth_hwid[$i]
	fi
    done
    for i in ${!sys_eth_mac[@]} ; do
	if ! have_cfg_eth_hwid ${sys_eth_mac[$i]} ; then
	    if [ -n "${cfg_eth_hwid[$i]}" ] ; then
		# cfg[#] has mac of another sys itf;
		# so, add another cfg itf for this mac
		# to the first available slot
		for (( j=0 ; true ; j++ )) ; do
		    if [ -z "${cfg_eth_hwid[$j]}" ] ; then
			cfg_eth_hwid[$j]=${sys_eth_mac[$i]}
			break 1
		    fi
		done
	    else
		cfg_eth_hwid[$i]=${sys_eth_mac[$i]}
	    fi
	fi
    done
}

mod_bootfile_eth_hwid ()
{
    local eth=$1 hwid=$2

    sed -i '/^interfaces {$/,/^}$/ {
	/^    ethernet '"$eth"' {$/ {
	    :join
	    /\n    }$/ {
		/hw-id: / s/\(hw-id:\) [0-9a-fA-F:]\+/\1 '"$hwid"'/
		/hw-id: /!	s/}$/    hw-id: '"$hwid"'\n    }/
		/link-detect/!	s/}$/    link-detect\n    }/
		q 0
	    }
	    N
	    b join
	}
    }' $BOOTFILE
}

add_bootfile_eth_hwid ()
{
    local eth=$1 hwid=$2

    sed -i '/^interfaces {$/,/^}$/ {
	/^}$/i\
    ethernet '"$eth"' {\
        hw-id: '"$hwid"'\
        link-detect\
    }
	}' $BOOTFILE
}

update_bootfile_eths ()
{
    local -i i

    for i in ${!cfg_eth_hwid[@]} ; do
	if grep -q "ethernet eth$i {" $BOOTFILE ; then
	    mod_bootfile_eth_hwid eth$i ${cfg_eth_hwid[$i]}
	else
	    add_bootfile_eth_hwid eth$i ${cfg_eth_hwid[$i]}
	fi
    done
}

search_config_if_wan () {
    grep "\<serial\>.*\<$1\>" $BOOTFILE >/dev/null
}

add_new_serial_if () {
    __config_additions=/tmp/__config_additions
    rm -f $__config_additions
    ip link show |
    sed -n '/^[0-9]*: wan[0-9]*:/ s/.* \([^:]*\):.*$/\1/p' |
    while read wan ; do
	if ! search_config_if_wan $wan ; then
	    echo "    serial $wan" >> $__config_additions
	fi
    done
    if [ -e $__config_additions ]; then
	rm -f /tmp/__bootfile
	sed '/^interfaces {$/ r '$__config_additions \
	    $BOOTFILE > /tmp/__bootfile
	mv /tmp/__bootfile $BOOTFILE
	rm -f $__config_additions
    fi
}

proc_flags ()
{
    # reset_promiscous_arp_response
    echo 1 > /proc/sys/net/ipv4/conf/default/arp_filter 
    # set_ip_forwarding
    echo 1 > /proc/sys/net/ipv4/ip_forward

    # if a primary address is removed from an interface promote and
    # secondary available
    echo 1 > /proc/sys/net/ipv4/conf/all/promote_secondaries
}

## Update the version information
update_version_info () {
    if [ -f ${vyatta_sysconfdir}/version.master ]; then
	cp ${vyatta_sysconfdir}/version.master ${vyatta_sysconfdir}/version
    fi
}

## Clear out apt config file--it will be filled in by rtrmgr
clear_apt_config()
{
    cat /dev/null >/etc/apt/sources.list || true
}

## snmp should be a separate package,
## but for now load the kernel module here
add_snmp_stats_module()
{
    modprobe ipt_rlsnmpstats || true
}

set_reboot_on_panic()
{
    echo 1 > /proc/sys/kernel/panic_on_oops
    echo 60 > /proc/sys/kernel/panic
}

clear_or_override_config_files ()
{
    for conf in motd.tail ntp.conf syslog.conf logrotate.d/messages \
        snmp/snmpd.conf snmp/snmptrapd.conf keepalived/keepalived.conf \
        ipvsadm.rules default/ipvsadm resolv.conf
    do
	if [ -f /etc/$conf ] ; then
	    cat /dev/null > /etc/$conf || true
	fi
    done
    for conf in motd.tail syslog.conf; do
	cp $vyatta_sysconfdir/$conf /etc/$conf
    done
    cp $vyatta_sysconfdir/logrotate_messages /etc/logrotate.d/messages
    cp $vyatta_sysconfdir/default_ssh /etc/default/ssh
    # ssh v1. remove the empty key file
    rm -f /etc/ssh/ssh_host_key
}

start () {
    clear_or_override_config_files || \
	log_failure_msg "can\'t reset config files"
    set_reboot_on_panic || \
	log_failure_msg "can\'t set reboot on panic"
    load_cfg_eth_hwid || \
	log_failure_msg "can\'t load interface hwids"
    update_cfg_eth_hwid || \
	log_failure_msg "can\'t resolve interface hwids"
    update_bootfile_eths || \
	log_failure_msg "can\'t update config interfaces"
    add_new_serial_if || \
	log_failure_msg "can\'t add serial interfaces"
    proc_flags  || \
	log_failure_msg "can\'t reset proc flags"
    update_version_info
    clear_apt_config
    add_snmp_stats_module
}

case "$ACTION" in
    start) start ;;
    stop|restart|force-reload) true ;; # nothing to stop/restart
    *)	log_failure_msg "action unknown: $ACTION" ;
	false ;;
esac

exit $?

# Local Variables:
# mode: shell-script
# sh-indentation: 4
# End: