#!/bin/bash

. ${TOOLKIT}-functions.sh

# cleanup old versions
#
purgefiles /etc/proftpd/anonymous.conf

# check if /bin/false is in /etc/shells
# (needed to allow ftp logins on non-login accounts)
#
grep -q "^/bin/false$" /etc/shells || {
	echo "  adding /bin/false to /etc/shells"
	echo "/bin/false" >>/etc/shells || exit $?
}


#----------------------------------------------------------------
# build chrooted access users/groups entries
#----------------------------------------------------------------

msg="\n\tyou must define entryes as  user:ftphome"

chroot_users=`	jtconf ftp.chroot_users 2>/dev/null	| tr ',' ' '`

for entry in $chroot_users
do
	user=$(echo "$entry" | cut -d':' -f1)
	ftphome=$(echo "$entry" | cut -d':' -f2)
	trush=$(echo "$entry" | cut -d':' -f3)

	[ "$ftphome" = "" ]	&& exit_err 1 "no ftphome in '$entry' $msg"
	[ "$trush" != "" ]	&& {
		echo -e "WARNING: ignored entry '$entry'"
		echo -e "   format for ftp.chroot_users is changed since 1.0-ku2.3 (2015/09) $msg"
		continue
	}

	entry=$(getent passwd $user) || exit_err 1 "user '$user' not existent"
	group=$(echo $entry | cut -d':' -f4)
	home=$(echo $entry | cut -d':' -f6)

	printf "   user  %-16s chrooted in %s\n" "$user:$group" $ftphome

	[ -d $home ] || {
		mkdir -p $home
		chown $user:$group $home
		chmod 700 $home
		echo "    homedir '$home' created"
	}
	updatelink $ftphome $home/ftp-home
done

#----------------------------------------------------------------
# 2018.03.20 lc
# - anonymous ftp now is optional
#----------------------------------------------------------------

target="/etc/proftpd/ku-anonymous.conf"

if $(getconfirm ftp.enable_anonymous)
then
	installfile ku-anonymous.conf	$target	root:root 440
else
	installfile ku-empty.conf	$target	root:root 440
fi

#----------------------------------------------------------------
# 2018.03.20 lc
# - added tls support, optional (note: reuquires srv-ssl module
#   and a valid certificate for ssl, see ku-tls.conf and
#   remember to add "ftp" to ssl.units for srv-ssl module)
#----------------------------------------------------------------

target="/etc/proftpd/ku-tls.conf"

if $(getconfirm ftp.enable_tls)
then
	installfile ku-tls.conf		$target	root:root 440
else
	installfile ku-empty.conf	$target	root:root 440
fi


add_init_script 50 proftpd

$SOMETHING_CHANGED && {
	sh /etc/init.d/proftpd restart
}

exit 0
