#!/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 $2 } # Generate random username and password USERNAME=$1 PASSWORD=$2 # User's home directory USER_HOME="/home/sftpusers/$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." 2 fi # Get the group ownership of the 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 directory under /home/sftpusers/ mkdir -p $USER_HOME useradd -d $USER_HOME $USERNAME if [ $? -ne 0 ]; then error_exit "Failed to create user $USERNAME." 4 fi echo "$USERNAME:$PASSWORD" | chpasswd # Create a symlink in the user's 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." 5 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." 6 fi log "$USERNAME added to group $ROOT_GROUP" # Adjust permissions and ownership for the user's directory chown $USERNAME:$ROOT_GROUP $USER_HOME chmod 750 $USER_HOME # 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\" }" exit 0