#!/bin/sh

if [ ! -f /usr/local/share/ca-certificates/Microsoft_Root_Certificate_Authority_2011.crt ]; then
    ln -s /usr/lib/te-agent/Microsoft_Root_Certificate_Authority_2011.crt /usr/local/share/ca-certificates/
    update-ca-certificates
fi

OLD_CONFIG=/etc/te-agent.cfg
NEW_CONFIG=/etc/te-agent.cfg.sample

# Update configuration file.
if [ -f "$OLD_CONFIG" ]; then
    # Make backup.
    rm -f "$OLD_CONFIG".backup.*

    # Ensure the config file is only readable/writeable by root before we make a backup
    # copy of it
    chmod 600 "$OLD_CONFIG"

    cp "$OLD_CONFIG" "${OLD_CONFIG}.backup.$(date -u +%Y%m%d%H%M)"

    # Ensure that the old config file ends with a new line.
    if [ $(tail -c1 $OLD_CONFIG | wc -l) -eq 0 ]; then
        echo >> $OLD_CONFIG
    fi

    # Add new keys to the old configuration file, keeping the old values.
    for key in `cut -d= -f1 $NEW_CONFIG`; do
        if ! grep -q ^"$key"= "$OLD_CONFIG"; then
            grep ^"$key"= "$NEW_CONFIG" >> "$OLD_CONFIG"
        fi
    done
else
    # If there is no old configuration, create the first version.
    cp "$NEW_CONFIG" "$OLD_CONFIG"

    # Ensure the config file is only readable/writeable by root
    chmod 600 "$OLD_CONFIG"
fi

exit 0
