#!/usr/bin/env bash

set -e
export PATH="$PATH:/usr/sbin:/sbin"

# Ensure script is run as root
if [ "$(id -u)" -ne 0 ]; then
    echo "Error: This script must be run as root." >&2
    echo "Switch to root first using: su -" >&2
    exit 1
fi

TARGET_USER="${1:-$SUDO_USER}"

if [ -z "$TARGET_USER" ]; then
    read -rp "Enter the non-root username to grant sudo access: " TARGET_USER
fi

if ! id "$TARGET_USER" &>/dev/null; then
    echo "Error: User '$TARGET_USER' does not exist." >&2
    exit 1
fi

# 1. Check if sudo package is installed
if command -v sudo &>/dev/null; then
    echo "==> 'sudo' is already installed, skipping installation."
else
    echo "==> Updating package indices and installing sudo..."
    apt update -y && apt install -y sudo
fi

# 2. Check if user is already in the sudo group
if groups "$TARGET_USER" | grep -qw "sudo"; then
    echo "==> User '$TARGET_USER' is already in the sudo group."
else
    echo "==> Adding '$TARGET_USER' to the 'sudo' group..."
    usermod -aG sudo "$TARGET_USER"
    echo "Note: '$TARGET_USER' must log out and back in for group changes to apply."
fi

echo "Done!"
