#!/bin/bash

# This script creates a new user, generates a random password for them,
# and adds them to the sudo group.
# IMPORTANT: This script must be run with sudo privileges.

# --- Configuration ---
USERNAME="n8nuser"
# ---

# 1. Check for sudo/root privileges
if [ "$(id -u)" -ne 0 ]; then
  echo "This script must be run as root or with sudo." >&2
  exit 1
fi

# 2. Check if user already exists
if id -u "$USERNAME" >/dev/null 2>&1; then
  echo "User '$USERNAME' already exists. Exiting."
  exit 0
fi

# 3. Create the user
echo "Creating user '$USERNAME'..."
useradd -m -s /bin/bash "$USERNAME"
if [ $? -ne 0 ]; then
  echo "Failed to create user '$USERNAME'. Exiting." >&2
  exit 1
fi

# 4. Generate and set password
echo "Generating password for '$USERNAME'..."
PASSWORD=$(head /dev/urandom | tr -dc A-Za-z0-9_.- | head -c 24)
echo "$USERNAME:$PASSWORD" | chpasswd
if [ $? -ne 0 ]; then
  echo "Failed to set password for '$USERNAME'." >&2
  # Clean up by deleting the user if password set fails
  userdel -r "$USERNAME"
  exit 1
fi

# 5. Add user to the sudo group
echo "Adding user '$USERNAME' to the 'sudo' group..."
usermod -aG sudo "$USERNAME"
if [ $? -ne 0 ]; then
  echo "Failed to add user to the sudo group." >&2
  exit 1
fi

# 6. Display the result
echo ""
echo "-----------------------------------------------------"
echo "User '$USERNAME' created successfully."
echo "Generated Password: $PASSWORD"
echo "Please save this password in a secure location."
echo "-----------------------------------------------------"

exit 0
