#!/usr/bin/env sh
#
# This file is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This file is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with This file.  If not, see <http://www.gnu.org/licenses/>.

set -e

progname="guix-hook"

usage()
{
    progname="$1"
    printf "Usage: %s <sysusers|help>\n\n" "${progname}"
}

# We want /etc/guix/acl to be readable by everybody to enable users to
# be able to find out if a given substitute is enabled or not. This is
# in this hook instead of the PKGBUILD as we need to fix the
# permissions, even if a previous /etc/guix/acl file is already there.
guix_fix_etc_guix_acl_permissions()
{
    # Use the same permissions than PureOS as Trisquel and
    # guix-install.sh don't set user/other read permissions on
    # /etc/guix/acl and while on guix system, this file has read
    # permission, it doesn't have any write permissions.
    chmod 644 /etc/guix/acl
}

# Distributions like PureOS or Trisquel do enable substitute servers
# by default.
guix_enable_substitutes()
{
    grep -q \
	 '#8D156F295D24B0D9A86FA5741A840FF2D24F60F7B6C4134814AD55625971B394#' \
	 /etc/guix/acl || \
	guix archive --authorize < /usr/share/guix/ci.guix.gnu.org.pub


    grep -q \
	 '#7D602902D3A2DBB83F8A0FB98602A754C5493B0B778C8D1DD4E0F41DE14DE34F#' \
	 /etc/guix/acl || \
	guix archive --authorize < /usr/share/guix/bordeaux.guix.gnu.org.pub
}

# Adapted from the GNU Guix manual, in the section 2.2.1 ("Build
# Environment Setup").
guix_add_build_users()
{
    groupadd --system guixbuild
    for i in $(seq -w 1 10);
    do
        useradd -g guixbuild -G guixbuild           \
                -d /var/empty -s "$(which nologin)" \
                -c "Guix build user $i" --system    \
                guixbuilder"${i}";
    done
}

guix_remove_build_users()
{
    for i in $(seq -w 1 10);
    do
        userdel guixbuilder"${i}";
    done
    groupdel guixbuild
}

case "$1" in
    add_build_users)
        guix_add_build_users ;;

    remove_build_users)
        guix_remove_build_users ;;

    fix_etc_guix_acl_permissions)
        guix_fix_etc_guix_acl_permissions;;

    enable_substitutes)
        guix_enable_substitutes;;

    *)
        echo "Invalid command ""'$1'""."
        usage "${progname}"
        exit 64 # EX_USAGE
        ;;
esac

exit 0
