#!/bin/bash

## Copyright (C) 2024 - 2025 ENCRYPTED SUPPORT LLC <adrelanos@whonix.org>
## See the file COPYING for copying conditions.

## passwordless-root - a tool for root to easily set up passwordless `sudo` for user `user`

set -x
set -e
set -o pipefail
set -o errtrace
set -o nounset

true "$0: START."

true "$0: INFO: Setting up passwordless sudo..."

command -v tee >/dev/null
## Atomic writes.
command -v sponge >/dev/null
## sudo configuration syntax check and atomic writes.
command -v visudo >/dev/null

if [ ! "$(id -u)" = "0" ]; then
  true "$0: ERROR: This program must be run as root!"
  exit 1
fi

if ! test -d "/etc/sudoers.d/" ; then
  true "$0: ERROR: Folder /etc/sudoers.d/ does not exist! Is sudo installed?"
  exit 1
fi

if ! test -w "/etc/sudoers.d/" ; then
  true "$0: ERROR: Folder /etc/sudoers.d/ is not writable!"
  exit 1
fi

passwordless_sudo_etc() {
  echo "user ALL=(ALL:ALL) NOPASSWD:ALL" | SUDO_EDITOR="" VISUAL="" EDITOR=tee visudo -f /etc/sudoers.d/nopassword >/dev/null
  true "\
$0: INFO: OPTIONAL:
sudo cat /etc/sudoers.d/nopassword
"
}

passwordless_sudo_qubes_rw() {
  if ! test -d /rw/config ; then
    true "$0: ERROR: folder /rw/config does not exist!"
    exit 1
  fi

  if ! test -r /rw/config/rc.local ; then
    true "$0: ERROR: file /rw/config/rc.local does not exist or is unreadable!"
    exit 1
  fi

  true "$0 INFO: Creating file...: /etc/sudoers.d/nopassword"

  ## Temporary passwordless sudo until reboot.
  echo "user ALL=(ALL:ALL) NOPASSWD:ALL" | SUDO_EDITOR="" VISUAL="" EDITOR=tee visudo -f /etc/sudoers.d/nopassword >/dev/null

  true "$0: INFO: Appending to file...: /rw/config/rc.local"

  ## Permanent passwordless sudo after reboot.
  append-once /rw/config/rc.local 'echo "user ALL=(ALL:ALL) NOPASSWD:ALL" | SUDO_EDITOR="" VISUAL="" EDITOR=tee visudo -f /etc/sudoers.d/nopassword >/dev/null' >/dev/null

  if ! test -x /rw/config/rc.local ; then
    chmod +x /rw/config/rc.local
  fi

  true "\
$0: INFO: OPTIONAL:
sudo cat /etc/sudoers.d/nopassword
sudo cat /rw/config/rc.local
"
}

if test -f /usr/share/qubes/marker-vm ; then
  if [ "${1:-}" = '--qubes-rw' ]; then
    passwordless_sudo_qubes_rw
  else
    passwordless_sudo_etc
  fi
else
  passwordless_sudo_etc
fi

true "$0: INFO: SUCCESS."
true "$0: END: OK."
