#!/bin/bash LOG_FILE="/home/jelastic/add-sftp-user-addon/logs/script_output.log" VERBOSE=1 # Set to 1 for verbose mode, 0 for normal mode log() { local timestamp=$(date +"%Y-%m-%d %H:%M:%S") echo "$timestamp - $1" >> $LOG_FILE if [ "$VERBOSE" -eq 1 ]; then echo "$timestamp - $1" fi } error_exit() { log "ERROR: $1" exit 1 } # Generate random username and password USERNAME=$1 PASSWORD=$2 # User's home directory USER_HOME="/home/$USERNAME" # The shared directory ROOT_DIRECTORY="/var/www/webroot/ROOT" log "Script started" # Ensure the ROOT_DIRECTORY exists if [ ! -d "$ROOT_DIRECTORY" ]; then error_exit "ROOT_DIRECTORY $ROOT_DIRECTORY does not exist." fi # Get the owner and group of the ROOT_DIRECTORY ROOT_OWNER=$(stat -c '%U' $ROOT_DIRECTORY) ROOT_GROUP=$(stat -c '%G' $ROOT_DIRECTORY) # Check if user already exists if id "$USERNAME" &>/dev/null; then log "ERROR: User $USERNAME already exists." exit 3 fi # Create user with their own home directory useradd -m $USERNAME if [ $? -ne 0 ]; then error_exit "Failed to create user $USERNAME." fi echo "$USERNAME:$PASSWORD" | chpasswd # Create a symlink in the user's home directory pointing to the shared ROOT_DIRECTORY ln -s $ROOT_DIRECTORY $USER_HOME/ROOT if [ $? -ne 0 ]; then error_exit "Failed to create symlink for $USERNAME." fi log "Symlink created for $USERNAME pointing to $ROOT_DIRECTORY" # Set user's group to the ROOT_GROUP usermod -aG $ROOT_GROUP $USERNAME if [ $? -ne 0 ]; then error_exit "Failed to modify groups for $USERNAME." fi log "$USERNAME added to group $ROOT_GROUP" # Check if the user-specific directory already exists USER_SPECIFIC_DIR="$ROOT_DIRECTORY/$USERNAME" if [ ! -d "$USER_SPECIFIC_DIR" ]; then # Create a user-specific directory inside ROOT_DIRECTORY mkdir $USER_SPECIFIC_DIR fi # Adjust permissions and ownership for the user-specific directory chown $USERNAME:$ROOT_GROUP $USER_SPECIFIC_DIR chmod 750 $USER_SPECIFIC_DIR # Owner has rwx, group has r-x, others have no permissions # Adjust permissions and ownership for the ROOT_DIRECTORY chown -R :$ROOT_GROUP /var/www/webroot/ROOT/ find /var/www/webroot/ROOT/ -type d -exec chmod 770 {} \; # For directories find /var/www/webroot/ROOT/ -type f -exec chmod 660 {} \; # For files # Set the SetGID bit on ROOT_DIRECTORY chmod g+s $ROOT_DIRECTORY HOSTNAME=$(hostname -f) log "Script completed for user $USERNAME with hostname $HOSTNAME" echo "{ \"USERNAME\": \"$USERNAME\", \"PASSWORD\": \"$PASSWORD\" }"