#!/bin/sh
# postinst script for chrony
#
# see: dh_installdeb(1)

set -e


# targets: configure|abort-upgrade|abort-remove|abort-deconfigure

case "$1" in
    configure)

        if ! getent passwd _chrony > /dev/null 2>&1
        then
            echo "Creating '_chrony' system user/group for the chronyd daemon…"
            adduser --force-badname \
                    --system \
                    --group \
                    --quiet \
                    --gecos "Chrony daemon" \
                    --home /var/lib/chrony \
                    --no-create-home _chrony
        fi

        # Change the owner of "/var/l{ib,og}/chrony" directories and their
        # subfiles to "_chrony" only if the user has not set the "user"
        # directive in chrony.conf
        if ! grep "^user" /etc/chrony/chrony.conf > /dev/null 2>&1; then
            chown -R _chrony:_chrony /var/lib/chrony
            if [ -d /var/log/chrony ]; then
                chown -R _chrony:_chrony /var/log/chrony
            fi
        fi

        if [ -z "$2" ]
        then
            # As this is a new install, generate a key.
            # Remove any keyfile left by a failed install.
            rm -rf /etc/chrony/chrony.keys
            KEYFILE=`tempfile -m 640 -n /etc/chrony/chrony.keys`
            PASSWORD=`head -c 8 /dev/urandom | tr '\0-\377' 'a-zA-Z0-9a-zA-Z0-9a-zA-Z0-9a-zA-Z0-9@@@@####'`
            echo "1 $PASSWORD" > $KEYFILE
        fi

        if `which ucf >/dev/null`
        then
          ucf --three-way /usr/share/chrony/chrony.conf /etc/chrony/chrony.conf
        fi

        # obsolete, instead use logrotate
        rm -rf /etc/cron.weekly/chrony
    ;;

    abort-upgrade|abort-remove|abort-deconfigure)
    ;;

    *)
        echo "postinst called with unknown argument \`$1'" >&2
        exit 1
    ;;
esac

# dh_installdeb will replace this with shell code automatically
# generated by other debhelper scripts.

#DEBHELPER#

exit 0
