#!/bin/bash
# passwordless-transition begin|installed
# Port of _passwordless_package_transition in the upstream Arch
# omarchy-settings.install. A package change revokes temporary sudo grants
# (omarchy-sudo-passwordless). Grants work again after a clean install.
set -u
action=$1
unset GLOBIGNORE
[[ -d /run && ! -L /run ]] || exit 1
[[ $(/usr/bin/stat -Lc '%u' /run) == "0" ]] || exit 1
! (( 8#$(/usr/bin/stat -Lc '%a' /run) & 022 )) || exit 1
umask 077
: >/run/omarchy-sudo-passwordless-package-removing || exit 1
# Same lock as omarchy-sudo-passwordless. /run/omarchy comes from the package
# tmpfiles: check that only root can write it, as upstream checks /run/lock.
[[ -d /run/omarchy && ! -L /run/omarchy ]] || exit 1
[[ $(/usr/bin/stat -Lc '%u' /run/omarchy) == "0" ]] || exit 1
! (( 8#$(/usr/bin/stat -Lc '%a' /run/omarchy) & 022 )) || exit 1
exec {lock_fd}>/run/omarchy/omarchy-sudo-passwordless.lock || exit 1
/usr/bin/flock -x -w 60 "$lock_fd" || exit 1
/usr/bin/rm -f -- /etc/sudoers.d/99-omarchy-nopasswd-* || exit 1
case $action in
  begin) ;;
  installed)
    for rule in /etc/sudoers.d/99-omarchy-nopasswd-*; do
      [[ ! -e $rule && ! -L $rule ]] || exit 1
    done
    [[ -f /etc/tmpfiles.d/omarchy-nopasswd-sudo.conf ]] || exit 1
    /usr/bin/rm -f -- /run/omarchy-sudo-passwordless-package-removing || exit 1
    ;;
  *) exit 1 ;;
esac
