#!/bin/bash

# Check if run as root
if [[ $EUID -ne 0 ]]; then
   echo "❌ This script must be run as root."
   exit 1
fi

# Prompt for input
read -rp "Enter the username to create: " USERNAME
read -rp "Enter full name (for comment field): " FULLNAME

# Check if user already exists
if id "$USERNAME" &>/dev/null; then
    echo "⚠️ User '$USERNAME' already exists."
else
    # Create the user
    adduser --gecos "$FULLNAME" "$USERNAME"
    echo "✅ User '$USERNAME' created."
fi

# Force password reset on first login
chage -d 0 "$USERNAME"

# Add user to sudo group
usermod -aG sudo "$USERNAME"
echo "✅ User '$USERNAME' added to sudo group."

# Create sudoers file with restricted commands
SUDOERS_FILE="/etc/sudoers.d/$USERNAME"

cat <<EOF > "$SUDOERS_FILE"
$USERNAME ALL=(ALL:ALL) ALL
$USERNAME ALL=(ALL) NOPASSWD:ALL
$USERNAME ALL=(ALL) !/bin/su, !/usr/bin/su, !/usr/bin/sudo su, !/usr/bin/sudo -i, !/usr/bin/sudo -u *, !/bin/bash, !/bin/sh, !/usr/local/bin/create_restricted_sudo_user.sh, !/usr/local/bin/secure_linux_login.sh
EOF

chmod 440 "$SUDOERS_FILE"
echo "✅ Sudo restrictions applied for '$USERNAME'."

# Summary
echo -e "\n✅ All done. '$USERNAME' can use sudo but cannot switch to root or other users."
