#!/bin/sh

set -e

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

# Add group for crontabs
getent group crontab > /dev/null 2>&1 || addgroup --system crontab

# Fixup crontab binary for new group 'crontab'.
if ! dpkg-statoverride --list /lib/systemd-cron/crontab_setgid > /dev/null ; then
    dpkg-statoverride --update --add root crontab 2755 /lib/systemd-cron/crontab_setgid
fi

# Remove leftover setgid bit from Vixie-cron
if dpkg-statoverride --list /usr/bin/crontab > /dev/null ; then
    dpkg-statoverride --remove /usr/bin/crontab
    chown root:root /usr/bin/crontab
    chmod 0755 /usr/bin/crontab
fi

# Fixup crontab , directory and files for new group 'crontab'
mkdir -p /var/spool/cron/crontabs
chown root:crontab /var/spool/cron/crontabs
chmod 1730 /var/spool/cron/crontabs
cd /var/spool/cron/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_name" != "$tab_owner" ]
        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

#DEBHELPER#
