#!/bin/sh
# Set up and run pure-ftpd server on Puppy Linux.
# Developed and tested on Puppy 2.16, 2.17
# Donated to Puppylinux, no rights reserved, etc etc. David Tangye: 22/07/2007

vProgName="`basename $0`"
vHost="`uname -n`"
vServerTitle="Pure-FTPd on $vHost"
vAnonAc=ftp
vFtpAdmin=ftpadmin

Add2Msg () {
	vMsgH=`expr $vMsgH + $1`
	shift
	vMsg="${vMsg}$@"
}

MakeWide () {
	local vW
	vW=${1:-$vMsgW}
	[ $vW -gt $vMsgW ] && vMsgW=$vW
}

ReportAnonSubDirs () {
		if [ "`echo "$vParms" | grep '[-]M' `" ] ; then
			Add2Msg 1 "\nThey can create subdirectories within their home."
			MakeWide 49
		else
			Add2Msg 1 "\nThey cannot create subdirectories within their home."
			MakeWide 52
		fi
}

RunStart () {
	vMsgH=15 ; vMsg=''
	vMsgW=40	# Minimum Width
	vParms=`Xdialog --title "$vServerTitle - オプション" \
			--backtitle "このオプションは最高のセキュリティを設定します:\n(root、管理者、匿名接続以外は鎖で繋がれています。)" \
			--left --separator \  \
			--ok-label "続ける" \
			--checklist "下のチェックボックスの変更は次のようになります ...
			
-u: rootと管理者アカウント経由の接続許可をクリアする。

-E: 匿名接続許可をクリアする（例えば、これをしばしば使うウェブブラウザ）。
 . . 接続は '$vAnonAc' という名前のアカウント経由になります。
 . . このアカウントがまだ設定されてなければ、次のステップはこのように処理されます。

-M: 匿名ユーザのサブディレクトリ作成を許可する事を選択
 . . （匿名接続が許可されたなら関連のみ）。

-A: 通常のユーザがホームから動き回らせる事をクリア
 . . （もしこれらのアカウントが接続を許可されていると
 . . これは root(無効です)も匿名(常に制限されています)
 . .  もなんの効果もありません。）
 " \
		36 85 4 \
		'-u' "root と管理者接続を止める" on \
		'-E' "匿名接続を止める" on \
		'-M' "匿名ユーザがサブフォルダを作る事を許可" off \
		'-A' "すべてのユーザをそのホーム内に制限する" on \
		2>&1 || echo .`
	[ "$vParms" == "." ] && exit

#	Root and Admin
	if [ "`echo "$vParms" | grep '[-]u' `" ] ; then
		vParms="`echo $vParms|sed 's/u/u 100/'`"
		Add2Msg 1 "* Root や管理者接続が許可されていません。"
	else
		Add2Msg 1 "* 警告: Root と管理者接続が許可されています。" ; MakeWide 50
	fi

#	Anonymous users
	if [ "`echo "$vParms" | grep "[-]E"`" ] ; then
		Add2Msg 1 "\n* 匿名接続は許可されていません。"
		[ "`echo "$vParms" | grep '[-]E -M' `" ] && vParms="`echo $vParms|sed 's/-E -M/-E/'`"
	else
		if [  -z "`awk -F\:  -v VNAME="$vAnonAc" '{if ($1 == VNAME) {print $1 ; exit}}' /etc/passwd`" ] ; then
			Xdialog --title "$vServerTitle - 匿名FTPアカウントの設定" \
			--backtitle " '$vAnonAc' という名前のアカウントで匿名接続が許可されています。" \
			--yesno "今すぐ '$vAnonAc' アカウントを作成しますか？"  9 60
			if [ $? ] ; then
				xterm -T "$vServerTitle" -fg blue -bg grey -e run-pureftpd $vAnonAc
				if [  "`awk -F\:  -v VNAME="$vAnonAc" '{if ($1 == VNAME) {print $1 ; exit}}' /etc/passwd`" ] ; then
					Add2Msg 3 "\n* Anonymous connections are allowed.\nHome directory for user $vAnonAc is created at '`awk -F \: -v FTP=$vAnonAc '{if ($1 == FTP) {print $6;exit}}' /etc/passwd`'.\nThese users are confined to their homes."
					MakeWide 47
					ReportAnonSubDirs
				else
					Add2Msg 2 "\n* WARNING: Anonymous connections will fail:\nNo anonymous account is defined on this server."
				fi
			else
				Add2Msg 2 "\n* WARNING: Anonymous connections will fail:\nNo anonymous account is defined on this server."
				MakeWide 47
			fi
		else
			Add2Msg 3 "\n* Anonymous connections are allowed, to `awk -F \: -v FTP=$vAnonAc '{if ($1 == FTP) {print $6;exit}}' /etc/passwd`.\n(These users are confined to this home)"
			MakeWide 60
			ReportAnonSubDirs
		fi
	fi

#	Normal users - roaming
	if [ "`echo "$vParms" | grep [-]A`" ] ; then
		Add2Msg 1 "\n* 通常の認証されたユーザはそのホーム内に制限されています。"
		MakeWide 57
	else
		Add2Msg 1 "\n* 警告: 通常の認証されたユーザはそのホームを越えて動き回る事ができます。"
		MakeWide 67
	fi
	
	Add2Msg 3 "\n\nその他のオプションの設定:\n隠しファイルを表示、\nゆるいプロトコル（-b ドキュメントをご覧下さい）、\nディスク容量が90% 以上になったらアップロードを停止して下さい。" ; MakeWide 84
	# This is a late addition. Maybe I can simply hardcode the width to this!
	# I'll leave MakeWide in for now, in case things change.

#	Start/Stop the Server
	pure-ftpd -D -b -k 90 $vParms &
	Xdialog --title "$vServerTitle サーバ" \
		--backtitle "サーバがスタートしました。\n（詳しい情報は、 http://www.pureftpd.org/）" \
		--left \
		--ok-label "サーバの停止" \
		--msgbox "$vMsg\n\nこのウィンドウを閉じるとサーバが停止します。" $vMsgH $vMsgW
	vPid="`pidof pure-ftpd`"
	[ "$vPid" ] && kill $vPid
}

FixAccountFiles () {
	# Parameters: 1=[account], (for anon a/c only ->) 2=Account name etc 3=shell
	# Catering for bugs in adduser?

	vPwFile=/etc/passwd
	vUserGid="`tail -1 $vPwFile |cut -d\: -f4`"
	vTmpFile="/tmp/${vProgName}-`date "+%Y%m%d-%H%M%S"`"
	>$vTmpFile
	FixGroupFile $1 $vUserGid /etc/group   $vTmpFile
	FixGroupFile $1 $vUserGid /etc/gshadow $vTmpFile

	if [ "`tail -1 $vPwFile |cut -d\: -f1`" == "$1" ] ; then
		if [ "$2" ] ; then
			vRecs=`wc -l $vPwFile |sed -e 's/[[:blank:]]*//'|cut -d\  -f1`
			cp -a $vPwFile $vTmpFile
			awk -F \: -v OFS=":" -v LL="$vRecs" -v DESC5="$2" -v SHELL7="$3" '
			{if (NR == LL)
				{print $1 OFS $2 OFS $3 OFS $4 OFS DESC5 OFS $6 OFS SHELL7}
					else print}' $vTmpFile >$vPwFile
			if [ $? ] ; then
				rm $vTmpFile
			else
				echo "$vProgname Error: $vPwFile processing failure."
				exit
			fi
		fi
	else
		echo "$vProgname Error: $1 account creation failure, not in $vPwFile."
		exit
	fi
}
FixGroupFile () {
	# Parameters: 1=[accountName->GroupName], 2=[gid], 3=group or gshadow file, 4=tmpFile

	vGid="`tail -1 $3 |cut -d\: -f1|grep [[:digit:]]`"
	if [ -n "$vGid" ] && [ "$vGid" == "$2" ] ; then
		vRecs=`wc -l $3 |sed -e 's/[[:blank:]]*//'|cut -d\  -f1`
		cp -a $3 $4
		awk -F \: -v OFS=":" -v LL=$vRecs -v GRPNAME=$1 '
		{if (NR == LL) {print GRPNAME OFS $2 OFS $3 OFS $4} else print}' $4 >$3
		if [ ! $? ] ; then
			echo "$vProgname Error: $3 processing failure."
			exit
		fi
	fi
}
 
CreateAnonAccount () {
	cat <<EOF
 
 Creating accounts to support anonymous ftp ...
 	1. '$vFtpAdmin' account for ftp administration,
 	2. '$1' account for anonymous ftp.

    When prompted you will need to enter a password (twice) for each account,
 	For the ANONYMOUS ACCOUNT supply an EMPTY PASSWORD, ie just hit [Enter],
 	and ignore the advice and warnings about password lengths.
 	
EOF

	read -p "Hit [Enter] to proceed  [Ctrl-C] to abort -> "

	echo -e "\n1 - $vFtpAdmin account ..."
	adduser -h /root/$1 $vFtpAdmin 2>/dev/null
	FixAccountFiles $vFtpAdmin
	
	echo -e "\n2 - $1 account ..."
	adduser -h /root/$1  $1 2>/dev/null
	FixAccountFiles $1 "Anonymous ftp only,,," "/bin/false"

	mkdir /root/$1/upload
	chmod g+w /root/$1/upload

	cat >/root/$1/Readme <<EOF
You can only download file from this directory.
Upload files into the upload directory.
EOF

	cat >/root/$1/upload/Readme <<EOF
You can only download file from this directory,
and also upload more files into here.
EOF
	chown -R $vFtpAdmin /root/$1/*
	chown $vFtpAdmin /root/$1
}

	if [ "$1" ] ; then CreateAnonAccount $1 ; else RunStart ; fi