#!/usr/bin/env bash

set -e

if [[ "$EUID" -ne 0 ]]; then
  echo "Please run this script as root."
  exit 1
fi

if ! command -v dialog &>/dev/null; then
  echo "dialog is not installed."
  echo "Install with: sudo apt install dialog  |  sudo pacman -S dialog"
  exit 1
fi

TMPFILE=$(mktemp)
trap 'rm -f "$TMPFILE"' EXIT

USERS=$(awk -F: '$3 >= 1000 && $1 != "nobody" {print $1}' /etc/passwd)

MENU_ITEMS=()
for u in $USERS; do
  MENU_ITEMS+=("$u" "")
done

dialog --title "Add sudo user" \
  --menu "Select a user:" 15 50 8 \
  "${MENU_ITEMS[@]}" 2>"$TMPFILE"

RET=$?
USER=$(cat "$TMPFILE")

if [[ $RET -ne 0 || -z "$USER" ]]; then
  clear
  echo "Aborted."
  exit 0
fi

SUDO_FILE="/etc/sudoers.d/$USER"

if [[ -f "$SUDO_FILE" ]]; then
  dialog --msgbox "User '$USER' already has sudo privileges." 7 50
  clear
  exit 0
fi

dialog --yesno "Add user '$USER' to sudoers?" 7 50
if [[ $? -ne 0 ]]; then
  clear
  echo "Aborted."
  exit 0
fi

echo "$USER ALL=(ALL:ALL) ALL" > "$SUDO_FILE"
chmod 440 "$SUDO_FILE"

if ! /usr/sbin/visudo  -cf "$SUDO_FILE"; then
  rm -f "$SUDO_FILE"
  dialog --msgbox "Invalid sudoers file. Changes reverted." 7 60
  clear
  exit 1
fi

dialog --msgbox "User '$USER' was successfully added to sudoers." 7 60
clear

