##############################################################################################################
##    Script Name    : updateSFtpUser.sh                                                                    ##
##    Author         : Leon Lin                                                                             ##
##    Created on     : 01/26/2014                                                                           ##
##    Usage          : ./updateSFtpUser.sh						                    ##
##    Purpose        : Update sftpuser permissions			   				    ##
##                                                                                                          ##
##############################################################################################################
#!/bin/bash

#backup config
cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak

if grep -q "^#Match Group sftpuser" /etc/ssh/sshd_config ;then
        echo "sshd config updated, no need to update!"
	exit 0
else
	#replace sftpuser permission and group
	sed -i '/^Match Group sftpuser/,/^[ ]*ForceCommand internal-sftp*/s/^/#/' /etc/ssh/sshd_config
	sed -i '/^Match User sftpuser/,/^[ ]*AllowTCPForwarding no/s/^/#/' /etc/ssh/sshd_config
	sed -i '/^#Match User sftpuser/ i\Match User sftpuser\n       X11Forwarding no\n       AllowTCPForwarding no\n       ForceCommand internal-sftp -u 000\n ' /etc/ssh/sshd_config
fi



# chang user id/group and home directory
usermod -d /content/uploaded -m -u 65533 -g nobody -c "SFTPUser" sftpuser

if [ $? -ne 0 ];then
        echo "Failed to update sftpuser permissions, please maually run command \"usermod -d /content/uploaded -m -u 65533 -g nobody -c \"SFTPUser\" sftpuser\" after upgrade to grant it, then restart service sshd"
        exit 1
else
		service sshd restart || exit 1
        echo "Successfully updated sftpuser permissions."
fi
