#!/usr/bin/env bash
#Filename: ftp_add_account.sh

### Define Variables start

NEW_USER=$1
E_MAIL=$2
VU_PWD=$(tr -cd '[:alnum:]' < /dev/urandom | fold -w25 | head -n1)
VU_RESOURCE='/etc/vsftpd/vu_vsftpd.txt'
VU_DB='/etc/vsftpd/vu_vsftpd.db'
VU_CONFIG_DIR='/etc/vsftpd/vu_conf_dir'
FTP_DIR='/data/ftp'
FTP_ADDR='115.29.6.112'
FTP_PORT=60021
REPORT_FILE=/tmp/ftp_notification.txt

### Define Variables end

# Determine the incoming parameters
if [[ $# -ne 2 ]]
then
	echo 'Error:Please define the new ftp username and user E-mail.'
	exit 1;
fi

# If there is a new username in the vsftpd account list, it is automatically deleted
grep ${NEW_USER} ${VU_RESOURCE} >/dev/null 2>&1
if [[ $? -eq 0 ]]
then
	EXIST_USER_LINE=$(grep -n ${NEW_USER} ${VU_RESOURCE} | cut -d: -f1)
	EXIST_PASS_LINE=$((${EXIST_USER_LINE} + 1 ))
	sed -i "${EXIST_USER_LINE},${EXIST_PASS_LINE}d" ${VU_RESOURCE}
fi
	
echo ${NEW_USER} >> ${VU_RESOURCE}
echo ${VU_PWD} >> ${VU_RESOURCE}

# Generate FTP Account DB
db_load -T -t hash -f ${VU_RESOURCE} ${VU_DB}

# Generate notification text file
cat >${REPORT_FILE}<<EOF
Your FTP account information is as follows:
 - Username: ${NEW_USER}
 - Password: ${VU_PWD}
 - Address: ${FTP_ADDR}
 - Port: ${FTP_PORT}

Tips: Please keep it properly, thanks.
EOF

# Create PriviAccount of Account
cat > ${VU_CONFIG_DIR}/${NEW_USER} <<EOF
anon_world_readable_only=NO
write_enable=YES
local_umask=002
anon_upload_enable=YES
anon_mkdir_write_enable=YES
anon_other_write_enable=YES
local_root=${FTP_DIR}
EOF

# Send the E-mail to the new ftp account && flush report file
mailx -s 'FTP account information' ${E_MAIL} <${REPORT_FILE} && :> ${REPORT_FILE}
