#!/bin/bash

# sudo-admin - grant passwordless sudo access to a user

set -euo pipefail

SUDOERS_DIR="/etc/sudoers.d"

if [ "$EUID" -ne 0 ]; then
    echo "Error: must be run as root" >&2
    exit 1
fi

if [ "$#" -gt 1 ]; then
    echo "Usage: sudo-admin [USERNAME]" >&2
    exit 1
fi

if [ "$#" -eq 1 ]; then
    USER_NAME="$1"
else
    # Default: user with UID 1000
    USER_NAME=$(getent passwd 1000 | cut -d: -f1)

    if [ -z "$USER_NAME" ]; then
        echo "Error: user with UID 1000 not found" >&2
        exit 1
    fi
fi

# Accept conservative Debian-style usernames only.
if [[ ! "$USER_NAME" =~ ^[a-z_][a-z0-9_-]*$ ]]; then
    echo "Error: invalid username '$USER_NAME'" >&2
    exit 1
fi

# Verify that the account exists.
if ! getent passwd "$USER_NAME" >/dev/null; then
    echo "Error: user '$USER_NAME' does not exist" >&2
    exit 1
fi

# Verify sudo is installed.
if ! command -v sudo >/dev/null 2>&1; then
    echo "Error: sudo is not installed" >&2
    exit 1
fi

# Verify the existing sudoers configuration before modifying it.
if ! visudo -c; then
    echo "Error: existing sudoers configuration is invalid" >&2
    exit 1
fi

# Add the user to administrative and log-reading groups
# only when those groups exist.
for GROUP in sudo adm systemd-journal; do
    if getent group "$GROUP" >/dev/null; then
        usermod -aG "$GROUP" "$USER_NAME"
    fi
done

# Create a temporary sudoers file in the target directory
# so that the final rename is atomic.
TMP_FILE=$(mktemp "$SUDOERS_DIR/.sudo-admin.XXXXXX")

cleanup() {
    if [ -n "${TMP_FILE:-}" ] && [ -e "$TMP_FILE" ]; then
        rm -f -- "$TMP_FILE"
    fi
}
trap cleanup EXIT

printf '%s ALL=(ALL:ALL) NOPASSWD: ALL\n' "$USER_NAME" > "$TMP_FILE"

chown root:root "$TMP_FILE"
chmod 0440 "$TMP_FILE"

# Validate the new rule before installing it.
if ! visudo -cf "$TMP_FILE"; then
    echo "Error: invalid sudoers rule" >&2
    exit 1
fi

SUDOERS_FILE="$SUDOERS_DIR/$USER_NAME-nopasswd"

# Preserve an existing dedicated rule for rollback.
BACKUP_FILE=""
if [ -e "$SUDOERS_FILE" ]; then
    BACKUP_FILE=$(mktemp "$SUDOERS_DIR/.sudo-admin-backup.XXXXXX")
    cp -a -- "$SUDOERS_FILE" "$BACKUP_FILE"
fi

# Install the rule atomically.
mv -f -- "$TMP_FILE" "$SUDOERS_FILE"
TMP_FILE=""

# Validate the complete configuration.
if ! visudo -c; then
    echo "Error: resulting sudoers configuration is invalid" >&2

    if [ -n "$BACKUP_FILE" ]; then
        mv -f -- "$BACKUP_FILE" "$SUDOERS_FILE"
    else
        rm -f -- "$SUDOERS_FILE"
    fi

    exit 1
fi

# Remove the backup after successful validation.
if [ -n "$BACKUP_FILE" ]; then
    rm -f -- "$BACKUP_FILE"
fi

echo "User '$USER_NAME' now has passwordless sudo access."
echo "Groups: $(id -nG "$USER_NAME")"
echo "Log out and log in again to apply supplementary group changes."
