#!/bin/bash
# SPDX-License-Identifier: GPL-3.0-or-later
# Copyright (C) 2015-2016, 2026 InterGenJLU
#
# at 3.2.5 — Job scheduling
# BLFS 13.0

configure() {
    set -e
    # Create the atd system user/group on the build chroot BEFORE the
    # subsequent `make install` invocation, which uses the Makefile-
    # baked `install -o atd -g atd` to create /var/spool/atjobs +
    # /var/spool/atspool. Without this, install fails with `invalid
    # user 'atd'`. The same sysusers.d entry is shipped to the archive
    # by the builder's overlay-files phase and re-processed at laptop
    # install time by pkm's canonical pre-hook + post_install below.
    systemd-sysusers "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")/files/usr/lib/sysusers.d/at.conf"
    ./configure --with-daemon_username=atd        \
                --with-daemon_groupname=atd       \
                SENDMAIL=/usr/sbin/sendmail       \
                --with-jobdir=/var/spool/atjobs   \
                --with-atspool=/var/spool/atspool \
                --with-systemdsystemunitdir=/usr/lib/systemd/system
}

build() {
    set -e
    make -j1
}

check() {
    set -e
    pkg_run_tests "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")/package.yml" \
        make test
}

do_install() {
    set -e
    make DESTDIR="$DESTDIR" install \
         docdir=/usr/share/doc/at-3.2.5 \
         atdocdir=/usr/share/doc/at-3.2.5

    # Set setuid bits — at + atd need setuid root for unprivileged users
    # to submit / dequeue jobs. Mode 4750 with group restriction to atd
    # per BLFS 13.0 canonical. Must be set here because tar-based
    # deployment strips setuid bits during extraction (pkm restores them
    # from tarball metadata post-extract; see pkm/installer.py:475-490).
    # Ownership is set in post_install on the live system because the
    # PEP 706 data filter in the deploy-extract path strips uid/gid.
    chmod 4750 "${DESTDIR}/usr/bin/at"
    chmod 4750 "${DESTDIR}/usr/sbin/atd"
}

post_install() {
    set -e
    # Process this package's /usr/lib/sysusers.d/at.conf entry now so
    # the atd user/group exist before the chown below resolves. Then
    # chown so the 4750 mode means atd-group-members + root, not
    # root-only.
    systemd-sysusers /usr/lib/sysusers.d/at.conf
    chown root:atd /usr/bin/at /usr/sbin/atd

    # PAM configuration
    cat > /etc/pam.d/atd << "EOF"
# Begin /etc/pam.d/atd
auth     required pam_unix.so
account  required pam_unix.so
password required pam_unix.so
session  required pam_unix.so
# End /etc/pam.d/atd
EOF

    systemctl enable atd
}
