#!/bin/bash

# Script to Add a New Pure-FTPd User
# Author: ChatGPT
# Description: Adds a new FTP user, sets a password, removes unnecessary shell files, and sets proper permissions.

# Check for root privileges
if [ "$(id -u)" -ne 0 ]; then
    echo "Please run this script as root or with sudo."
    exit 1
fi

# Prompt for FTP user details
read -p "Enter the FTP username: " FTP_USER
read -p "Enter the FTP group (default: ftpgroup): " FTP_GROUP
FTP_GROUP=${FTP_GROUP:-ftpgroup}

FTP_HOME_BASE="/home/ftpuser"
FTP_HOME="$FTP_HOME_BASE/$FTP_USER"

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

# Create FTP group if it doesn't exist
if ! getent group "$FTP_GROUP" > /dev/null; then
    echo "Creating group '$FTP_GROUP'..."
    groupadd "$FTP_GROUP"
fi

# Create FTP user and home directory
echo "Creating user '$FTP_USER'..."
useradd -d "$FTP_HOME" -m -s /usr/sbin/nologin -g "$FTP_GROUP" "$FTP_USER"

# Prompt to set password securely
echo "Set password for FTP user '$FTP_USER':"
passwd "$FTP_USER"

# Remove unnecessary shell files
echo "Removing unnecessary shell files from $FTP_HOME..."
rm -f "$FTP_HOME/.bash_logout" "$FTP_HOME/.bashrc" "$FTP_HOME/.profile"

# Set permissions for the user's home directory
echo "Setting permissions for $FTP_HOME..."
chmod 750 "$FTP_HOME"
chown "$FTP_USER:$FTP_GROUP" "$FTP_HOME"

# Configure Pure-FTPd virtual user
echo "Configuring Pure-FTPd virtual user..."
pure-pw useradd "$FTP_USER" -u "$FTP_USER" -d "$FTP_HOME"
pure-pw mkdb

# Restart Pure-FTPd to apply changes
echo "Restarting Pure-FTPd service..."
systemctl restart pure-ftpd

# Final confirmation
echo "FTP user '$FTP_USER' has been created successfully!"
echo "Home Directory: $FTP_HOME"
