#!/bin/bash
# $Id: 80-lbcheck_config 10 2014-04-07 14:31:40Z sanders $
#
# Creates /etc/default/bit-lbcheck with One Context values

LBDEFAULTS="/etc/default/bit-lbcheck"

PING=$(which ping)
[ -z "$PING" ] && PING="/bin/ping"

IP=$(which ip)
[ -z "$IP" ] && IP="/sbin/ip"

func_main() {
    V4=1
    V6=1
    [ -z "$LBGW"  -o -z "$LBIP"  -o -z "$LBNET"  -o -z "$LBMASK"  ] && V4=0
    [ -z "$LBGW6" -o -z "$LBIP6" -o -z "$LBNET6" -o -z "$LBMASK6" ] && V6=0

    MODE=unconfigured
    [ "$V4" = "1" -a "$V6" = "1" ] && MODE=both
    [ "$V4" = "1" -a "$V6" = "0" ] && MODE=ipv4
    [ "$V4" = "0" -a "$V6" = "1" ] && MODE=ipv6

    if [ "$MODE" = "unconfigured" ]; then
        func_writedefaults
        exit 0
    fi

    # Figure out available interfaces
    IFACES=$(ip ad sh | grep '^[[:alnum:]]' | cut -d' ' -f2 | sed -e 's/:$//' | xargs)
    LBIF=""

    # Iterate all, except the $OUTIF
    for IFACE in $IFACES
    do
        [ "$IFACE" = "lo" ] && continue

        $IP addr add $LBIP/$LBMASK dev $IFACE

        $PING -qc 5 -W 1 -I $LBIP $LBGW >/dev/null 2>&1
        RV=$?

        $IP addr del $LBIP/$LBMASK dev $IFACE

        if [ "$RV" = "0" ]; then
            LBIF=$IFACE
            break
        fi
    done

    if [ "$LBIF" = "" ]; then
        echo "Interface detection failed."
        rm -f $LBDEFAULTS
        exit 0
    fi

    func_writedefaults
}


func_writedefaults() {
    cat >$LBDEFAULTS <<EOT
# Defaults file for bit-lbcheck
# !! Modified by bit-one-context !!
#
# This is a shellscript which is evaluated by the shell

# Possible 'RUN' values:
# ipv4, ipv6, both
#
# Anything else is considered as 'do not run'.
RUN="$MODE"

# Check interval in seconds
INTERVAL=15

# IPv4 LB-configuration
LBGW="$LBGW"
LBIP="$LBIP"
LBNET="$LBNET"
LBMASK="$LBMASK"
LBIF="$LBIF"

# IPv6 LB-configuration
LBGW6="$LBGW6"
LBIP6="$LBIP6"
LBNET6="$LBNET6"
LBMASK6="$LBMASK6"
LBIF6="$LBIF"
EOT
    chown root:root $LBDEFAULTS
    chmod 644 $LBDEFAULTS
}



#########
func_main
exit 0
