#!/bin/bash
# Root helper for Atychia. sudoers allows only this path, with no
# password. It runs the same program pkexec would. logind emits
# SecureAttentionKey again for every Esc repeat, so a second start
# within 10 seconds, or while Atychia is already up, is ignored.
# SPDX-License-Identifier: GPL-2.0-or-later

if [[ "${1:-}" != "/usr/bin/atychia-launch" ]]; then
    echo "atychia-as-root: refused" >&2
    exit 1
fi
if [[ -z "${SUDO_UID:-}" ]]; then
    echo "atychia-as-root: SUDO_UID missing" >&2
    exit 1
fi
export PKEXEC_UID="$SUDO_UID"
shift

exec 9>/run/atychia-sak.lock
flock 9
now=$(date +%s)
prev=0
if [[ -f /run/atychia-sak.stamp ]]; then
    prev=$(cat /run/atychia-sak.stamp)
fi
if (( now - prev < 10 )); then
    exit 0
fi
if pgrep -x atychia >/dev/null; then
    exit 0
fi
printf '%s\n' "$now" > /run/atychia-sak.stamp
flock -u 9
exec /usr/bin/atychia-launch "$@"
