#!/bin/sh
set -e

# Analogous to Debian's ISC cron postinst script (for compatibility reasons)
crondir="/var/spool/cron"
action="$1"

if [ "$action" != configure ]
then
    exit 0
fi


# Make sure group "crontab" exists (needed for running SGID)
getent group crontab > /dev/null 2>&1 || addgroup --system crontab

# Make crontab(1) SGID
if ! dpkg-statoverride --list /usr/bin/crontab > /dev/null
then
    dpkg-statoverride --update --add root crontab 2755 /usr/bin/crontab
fi

# Adjust permissions for spool dir
# Can't use dpkg-statoverride for this because it doesn't cooperate nicely
# with cron alternatives such as bcron
if [ -d $crondir/crontabs ]
then
    # This must be in sync with misc.c:check_spool_dir()
	chown root:crontab $crondir/crontabs
    chmod 1730 $crondir/crontabs

    cd $crondir/crontabs
    set +e

    # Iterate over each entry in the spool directory, perform some sanity
    # checks (see CVE-2017-9525), and chown/chgroup the crontabs
    for tab_name in *
    do
        [ "$tab_name" = "*" ] && continue
        tab_links=`stat -c '%h' "$tab_name"`
        tab_owner=`stat -c '%U' "$tab_name"`

        if [ ! -f "$tab_name" ]
        then
            echo "Warning: $tab_name is not a regular file!"
            continue
        elif [ "$tab_links" -ne 1 ]
        then
            echo "Warning: $tab_name has more than one hard link!"
            continue
        elif [ "$tab_owner" != "$tab_name" ]
        then
            echo "Warning: $tab_name name differs from owner $tab_owner!"
            continue
        fi

		chown "$tab_owner:crontab" "$tab_name"
		chmod 600 "$tab_name"
    done
    set -e
fi

#DEBHELPER#

exit 0