#!/bin/sh

################################################################################
#
# Copyright (C) 2015 Cumulus Networks Inc. All rights reserved
#
################################################################################

# This script generates and installs platform specific sysctl config
# files into /etc/sysctl.d on the target file system.
#
# This script uses the facilities from ucf(1) to manage local
# configuration file changes made by the user.
#
# This script is called in the following contexts:
#
# - initramfs: during the first boot after the current platform type
#   is determined.  ucf(1) uses debconf so we have to be careful about
#   which debconf to use when we have no TTY.
#
# - dpkg upgrades via postinst: when installing a new version of the
#   cumulus-tools package.

initramfs="${DPKG_RUNNING_VERSION:-yes}"
if [ "$initramfs" = "yes" ] ; then
    # The legacy initramfs calls this script every boot.  Exit if
    # called before.
    [ -e /var/cache/cumulus/platform-sysctl ] && exit 0

    # We have no controlling TTY in initramfs context
    export DEBIAN_FRONTEND=noninteractive
fi

# Use ucf and ucfr to install and register the configuration file with
# the system.
# $1 - source file to install
# $2 - destination file
install_file()
{
    UCF_CMD="ucf --debconf-ok --three-way"
    [ "$quiet" = "y" ] && REDIR="> /dev/null 2>&1"

    eval $UCF_CMD "$1" "$2" $REDIR

    ucfr cumulus-platform "$2"
}

installdir="/etc/sysctl.d"

# Generate the platform specific sysctl files into a temporary
# directory.

# clean up for temporary directory
tmp_cleanup()
{
    rm -rf $tmpdir
}

tmpdir=$(mktemp -d) || {
    echo "Error: Unable to create temp directory."
    exit 1
}
trap tmp_cleanup EXIT QUIT

/usr/lib/cumulus/generate-sysctl --output-directory=$tmpdir || {
    echo "ERROR:  Problems generating platform sysctl files"
    exit 1
}

for f in $(ls $tmpdir) ; do
    install_file "$tmpdir/$f" "$installdir/$f"
done

if [ "$initramfs" = "yes" ] ; then
    mkdir -p /var/cache/cumulus
    touch /var/cache/cumulus/platform-sysctl
fi
