#!/bin/bash
#
# vdsm-store-net-config: store network configuration files persistently
#

. /usr/libexec/vdsm/ovirt_functions.sh

# ifcfg persistence directories
NET_CONF_DIR='/etc/sysconfig/network-scripts/'
NET_CONF_BACK_DIR='/var/lib/vdsm/netconfback'

# Unified persistence directories
RUN_CONF_DIR='/var/run/vdsm/netconf'
PERS_CONF_PATH='/var/lib/vdsm/persistence'
PERS_NET_CONF_PATH="$PERS_CONF_PATH/netconf"

PERSISTENCE=$1

ifcfg_node_persist() {
    for f in "$NET_CONF_BACK_DIR"/*;
    do
        [ ! -f "$f" ] && continue
        bf=`basename "$f"`
        if [ -f "$NET_CONF_DIR/$bf" ];
        then
            ovirt_store_config "$NET_CONF_DIR/$bf"
        else
            ovirt_safe_delete_config "$NET_CONF_DIR/$bf"
        fi
        rm "$NET_CONF_BACK_DIR/$bf"
    done
}

ifcfg_nonnode_persist() {
    # Remove the backed up configuration files thus marking the ones under
    # /etc/sysconfig as "safe".
    rm -rf "$NET_CONF_BACK_DIR"/*
}

node_persist_owned_ifcfgs() {
    for f in $(find "$NET_CONF_DIR" -type f); do
        if grep -q "# Generated by VDSM version" "$f"; then
            ovirt_store_config "$f"
        fi
    done
}

unified_node_persist() {
    unified_nonnode_persist
    # we need to persist ifcfg files as well so that they are available earlier
    # on boot time
    node_persist_owned_ifcfgs

    # oVirt node ovirt_store_config puts the dir in persistent storage and
    # bind mounts it in the original place. So that's all we really need to do.
    ovirt_store_config "$PERS_CONF_PATH"
}

unified_nonnode_persist() {
    # Remove stored non-VDSM network devices (BZ#1188251)
    ifcfg_nonnode_persist

    # Atomic directory copy by using the atomicity of overwriting a link
    # (rename syscall).
    TIMESTAMP=$(date +%s%N)
    PERS_CONF_SYMLINK=$PERS_NET_CONF_PATH
    PERS_CONF_DIR_ROOTNAME="$PERS_CONF_SYMLINK."
    PERS_CONF_NEW_DIR="$PERS_CONF_DIR_ROOTNAME$TIMESTAMP"
    PERS_CONF_NEW_SYMLINK="$PERS_CONF_SYMLINK.link.$TIMESTAMP"

    cp -r "$RUN_CONF_DIR" "$PERS_CONF_NEW_DIR"
    ln -s "$PERS_CONF_NEW_DIR" "$PERS_CONF_NEW_SYMLINK"
    mv -fT "$PERS_CONF_NEW_SYMLINK" "$PERS_CONF_SYMLINK"
    find "$PERS_CONF_PATH" -type d -path "$PERS_CONF_DIR_ROOTNAME*" | \
        grep -v "$PERS_CONF_NEW_DIR" | xargs rm -fr
}


if isOvirtNode
then
    # for node, persist the changed configuration files

    . /usr/libexec/ovirt-functions

    if [ "$PERSISTENCE" == "unified" ]; then
        unified_node_persist
    else
        ifcfg_node_persist
    fi
else
    if [ "$PERSISTENCE" == "unified" ]; then
        unified_nonnode_persist
    else
        ifcfg_nonnode_persist
    fi
fi
