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

set -e

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

case "$1" in
    configure)

        cp /usr/share/chrony/chrony.conf /etc/chrony/chrony.conf.new
        MAILUTC=""
        TZONE=""

        # look for real-time clock
        if [ -f /etc/adjtime ]; then
            TZONE=$(grep -E "UTC|LOCAL" /etc/adjtime)

        elif [ -f /etc/default/rcS ]; then
            .  /etc/default/rcS
            case "$UTC" in
                no|"") TZONE="LOCAL"
                ;;
                yes)  TZONE="UTC"
                ;;
            esac
        fi

        # set rtconutc for chrony
        case "$TZONE" in
            LOCAL) echo "# rtconutc" >> /etc/chrony/chrony.conf.new
            ;;
            UTC)  echo "rtconutc" >> /etc/chrony/chrony.conf.new
            ;;
            *)  echo "# rtconutc" >> /etc/chrony/chrony.conf.new
                MAILUTC="Chrony do not know how your clock is set: assuming local time.
If this is not correct edit /etc/chrony/chrony.conf. The comments
explain what to do."
            ;;
        esac

        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
            MAILPASSWORD="The password for chronyc is in $KEYFILE."

            if [ `echo $MAILUTC | wc -m` -gt 10 ]
            then
                # And tell root about the rtc setting
                if `which mail >/dev/null`
                then
                 echo "$MAILUTC" | mail -s "Chrony" root
                fi
            fi
        fi

        if `which ucf >/dev/null`
        then
          ucf /etc/chrony/chrony.conf.new /etc/chrony/chrony.conf
          rm /etc/chrony/chrony.conf.new
        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
