#!/bin/bash
#
# Takes as input a reference to an encoded configuration file
# and produces from that a kernel module file and a network
# configuration file. It then restarts the networking service
# and saves the configuration files.

. /usr/libexec/ovirt-functions

ME=$(basename "$0")
warn() { printf '%s: %s\n' "$ME" "$*" >&2; }
die() { warn "$*"; exit 1; }

try_h() { printf "Try \`$ME -h' for more information.\n" >&2; exit 1;}
try_help() { printf "Usage: \`$ME [config] [module output] [config output]\n" >&2; exit 1;}

case $# in
  0|1|2) warn "too few arguments"; try_help;;
  3) ;;
  *) warn "too many arguments"; try_help;;
esac

CONFIG=$1
OVIRT_KERNEL_MODULE_FILE=$2
OVIRT_CONFIG_OUTPUT_FILE=$3

modconf=$(awk '/^[ \t]*bonding=.+/ {
        match($0, "^[ \t]*bonding=(.+)", data)
        printf "data[2] = %s\n", data[2]

        if (match("[^[:alnum:]=_@-]", data[2]) >= 0) {
            printf "invalid bonding alias: \"%s\"\n", data[2];
            exit 1;
        }

        alias=data[2]

        printf("install %s bonding", alias)
    }' $CONFIG)

echo "$modconf" > $OVIRT_KERNEL_MODULE_FILE

networking=$(awk '/^[ \t]*ifcfg=/ {
    match($0, "^[ \t]*ifcfg=(.*)", data)
    split(data[1], ifcfg, "|")

    mac = ifcfg[1]
    iface = ifcfg[2]
    ifcfg_dir = "/files/etc/sysconfig/network-scripts"

    printf("rm %s/ifcfg-%s\n", ifcfg_dir, iface)
    printf("set %s/ifcfg-%s/DEVICE %s\n", ifcfg_dir, iface, iface)

    for (line in ifcfg) {
        if(line > 2) {
            match(ifcfg[line], "(^[^=]+)=(.*)", values)
            field=values[1]
            value=values[2]

            if(length(field) == 0) {
                print "Missing field name."
                exit 1
            }

            if(length(value) == 0) {
                print "Missing field value."
                exit 2
           }

            printf("set %s/ifcfg-%s/%s %s\n", ifcfg_dir, iface, field, value)
        }
    }

}' $CONFIG)

SUCCESS=$?

if [ $SUCCESS != 0 ]; then
    case $SUCCESS in
        1) error="missing field name";;
        2) error="missing field value";;
    esac

    die "Bad data received: ${error}"
fi

echo "$networking" > $OVIRT_CONFIG_OUTPUT_FILE

if [ -f $OVIRT_CONFIG_OUTPUT_FILE ]; then
    augtool $OVIRT_CONFIG_OUTPUT_FILE \
        && RESULT=0 || RESULT=1
    # FIXME do not store ifcfg-lo
    if ls /etc/sysconfig/network-scripts/ifcfg* >/dev/null 2>/dev/null; then
        ovirt_store_config /etc/sysconfig/network-scripts/ifcfg*
    fi
fi

exit $RESULT
