#!/bin/sh
set -eu

assert_fail() {
    if $1 2>&1; then
        echo "FAIL: command '$1' unexpectedly succeeded" >&2
        exit 1
    fi
}

assert_eq() {
    if [ "$1" != "$2" ]; then
        echo "FAIL: expected: '$2' actual: '$1'" >&2
        exit 1
    fi
}

assert_in() {
    if ! echo "$2" | grep -q "$1"; then
        echo "FAIL: '$1' not found in:" >&2
        echo "$2" >&2
        exit 1
    fi
}

stop_polkitd () {
    if [ -d /run/systemd/system ]; then
        systemctl stop polkit.service
    else
        # On non-systemd systems, polkitd is started as a traditional D-Bus
        # system service and is not managed by a service manager, so this is
        # the best we can do
        start-stop-daemon --stop --oknodo --quiet --exec /usr/lib/polkit-1/polkitd || true
        start-stop-daemon --stop --oknodo --quiet --exec /usr/libexec/polkitd || true
    fi
}

# lxc autopkgtest containers don't always have dbus already running
sudo service dbus start || :

if ! [ -e /run/dbus/system_bus_socket ]; then
    echo "SKIP: dbus system bus not running and could not be started"
    exit 77
fi

echo "TEST: pkexec"
# Members of the sudo group are allowed to do anything
sudo tee /etc/polkit-1/rules.d/00-test-allow.rules >/dev/null <<EOF
polkit.addRule(function(action, subject) {
    if (subject.isInGroup("sudo")) {
        return polkit.Result.YES;
    }
    return polkit.Result.NOT_HANDLED;
});
EOF
# Anyone else is not allowed to do anything (deny comes after allow in
# alphabetical order, so the other rule wins)
sudo tee /etc/polkit-1/rules.d/00-test-deny.rules >/dev/null <<EOF
polkit.addRule(function(action, subject) {
    return polkit.Result.NO;
});
EOF

# make sure the policy is reloaded, without any race conditions
stop_polkitd

# sudo group member can pkexec because we installed policy that says so
assert_eq "$(pkexec id -u)" "0"
assert_fail "sudo -u daemon pkexec id"
echo "OK"
sudo rm -f /etc/polkit-1/rules.d/00-test-allow.rules
sudo rm -f /etc/polkit-1/rules.d/00-test-deny.rules
