#! /bin/bash
# Wing FTP Server 2003-2024 wftpserver.com All Rights Reserved 
# SETUP SCRIPT FOR MAC OS

portvalid="0"
adminport="5466"
username="administrator"
password="wingftp"

STARTUP_WFTP="/Library/StartupItems/WingFTPServer"
OPENSSL_LIB="/usr/local/ssl/lib"

APPNAME="$0"
while [ -h "$APPNAME" ]; do
        LINK=`ls -ld "$APPNAME"`
        LINK=`expr "$LINK" : '.*-> \(.*\)'`
        if [ "`expr "$link" : '/.*'`" = 0 ]; then
                DIR=`dirname "$APPNAME"`
                APPNAME="$DIR/$LINK"
        else
                APPNAME="$LINK"
        fi
done
WING_HOME=`dirname $APPNAME`
WING_HOME=`cd $WING_HOME && pwd`

alert() {
	echo -n "$1? [y/N]: "
	read MESSAGE
	expr "$MESSAGE" : ' *[yY].*' > /dev/null
}

if [ "$UID" -ne "0" ]; then
  echo "The setup script is required to run under root privileges."
  echo "Please try again like this:  sudo ./setup.sh"
  exit
fi

echo "Welcome to the Wing FTP Server setup wizard!"
echo "Please setup administrator account for Wing FTP Server."
echo "This account is very important as it will be used to administrate your server."
echo -n "Enter the administrator name: "
read username
while [ -z "$username" ]; do
   echo "Admin name can not be empty!"
   echo ""
   echo -n "Enter the administrator name: "
   read username
done
echo -n "Enter the administrator password: "
read password
while [ -z "$password" ]; do
   echo "Admin password can not be empty!"
   echo ""
   echo -n "Enter the administrator password: "
   read password
done

password="${password}WingFTP"

echo ""
echo "Please specify a port that web based administration will be listening to."
echo -n "Enter the listener port(default is 5466): "
read adminport
if [ -z "$adminport" ]; then
    adminport="5466"
fi


#check whether adminport is a valid port
netstat -ln |awk '/^tcp/ {print $4}' |grep -q ":$adminport$" || portvalid="1" 1>/dev/null 2>&1
echo "$adminport" |grep -Eq '[^0-9]' && portvalid="0" 1>/dev/null 2>&1
while [ -z "$adminport" ] || [ "$portvalid" -eq "0" ] || [ "$adminport" -lt "1" ] || [ "$adminport" -gt "65535" ]; do
    echo "Port $adminport is an invalid port or being used, please stop WingFTP service first."
    echo ""
    echo -n "Enter the listener port(default is 5466): "
    read adminport
    if [ -z "$adminport" ]; then
        adminport="5466"
    fi
    portvalid="0"
    netstat -ln |awk '/^tcp/ {print $4}' |grep -q ":$adminport$" || portvalid="1" 1>/dev/null 2>&1
    echo "$adminport" |grep -Eq '[^0-9]' && portvalid="0" 1>/dev/null 2>&1
done

passmd5=`echo -n "$password"|shasum -a 256|cut -d' ' -f1`

if [ -z "$passmd5" ]; then
    passmd5=`md5 -s "$password"|cut -d' ' -f4`
fi

#kill the existed wftpserver process
WFTP_PID=`ps -ef | grep "\\.\\/wftpserver" | grep -v grep | awk '{print $2}'`
if [ ! -z "$WFTP_PID" ]; then
  kill -9 $WFTP_PID & 1>/dev/null 2>&1
fi


if [ ! -f "$WING_HOME/Data/_ADMINISTRATOR/admins.xml" ]; then
mkdir -p "$WING_HOME/Data/_ADMINISTRATOR" 1>/dev/null 2>&1
touch "$WING_HOME/Data/_ADMINISTRATOR/admins.xml"
cat > "$WING_HOME/Data/_ADMINISTRATOR/admins.xml" <<-EOF
<?xml version="1.0" ?>
<ADMIN_ACCOUNTS Description="Wing FTP Server Admin Accounts">
<ADMIN><Admin_Name>$username</Admin_Name><Password>$passmd5</Password><Type>0</Type><Readonly>0</Readonly></ADMIN>
</ADMIN_ACCOUNTS>
EOF
fi

if [ ! -f "$WING_HOME/Data/_ADMINISTRATOR/settings.xml" ]; then
mkdir -p "$WING_HOME/Data/_ADMINISTRATOR" 1>/dev/null 2>&1
touch "$WING_HOME/Data/_ADMINISTRATOR/settings.xml"
cat > "$WING_HOME/Data/_ADMINISTRATOR/settings.xml" <<-EOF
<?xml version="1.0" ?>
<Administrator Description="Wing FTP Server Administrator Options">
    <HttpPort>$adminport</HttpPort>
    <HttpSecure>0</HttpSecure>
    <SSLName>wftp_default_ssl</SSLName>
    <AdminLogfileEnable>1</AdminLogfileEnable>
    <AdminLogfileFileName>Admin-%Y-%M-%D.log</AdminLogfileFileName>
    <AdminLogfileMaxsize>0</AdminLogfileMaxsize>
    <EnablePortUPnP>0</EnablePortUPnP>
</Administrator>
EOF
fi

sed -i '' -e "s/<\/ADMIN_ACCOUNTS>/<ADMIN><Admin_Name>$username<\/Admin_Name><Password>$passmd5<\/Password><Type>0<\/Type><Readonly>0<\/Readonly><\/ADMIN><\/ADMIN_ACCOUNTS>/" "$WING_HOME/Data/_ADMINISTRATOR/admins.xml"
sed -i '' -e "s/\(<HttpPort>\).*\(<\/HttpPort>\)/\1$adminport\2/" "$WING_HOME/Data/_ADMINISTRATOR/settings.xml"
chmod -R 600 "$WING_HOME/Data"

if [ -d "$WING_HOME/session" ]; then
	chmod -R 600 "$WING_HOME/session"
fi

if [ -d "$WING_HOME/session_admin" ]; then
	chmod -R 600 "$WING_HOME/session_admin"
fi

if [ -d "$WING_HOME/Log/Admin" ]; then
	chmod -R 600 "$WING_HOME/Log/Admin"
fi


#add openssl library to /usr/local/ssl/fips/lib
#if [ ! -d "$OPENSSL_LIB" ]; then
#mkdir -p $OPENSSL_LIB 1>/dev/null 2>&1
#fi

#if [ ! -f "$OPENSSL_LIB/libcrypto.1.0.0.dylib" ]; then
#cp $WING_HOME/libcrypto.1.0.0.dylib $OPENSSL_LIB/libcrypto.1.0.0.dylib
#cp $WING_HOME/libcrypto.dylib $OPENSSL_LIB/libcrypto.dylib
#fi

#if [ ! -f "$OPENSSL_LIB/libssl.1.0.0.dylib" ]; then
#cp $WING_HOME/libssl.1.0.0.dylib $OPENSSL_LIB/libssl.1.0.0.dylib
#cp $WING_HOME/libssl.dylib $OPENSSL_LIB/libssl.dylib
#fi

mkdir -p $STARTUP_WFTP 1>/dev/null 2>&1

touch "$STARTUP_WFTP/StartupParameters.plist"
touch "$STARTUP_WFTP/WingFTPServer"
chmod 644 "$STARTUP_WFTP/StartupParameters.plist"
chmod 755 "$STARTUP_WFTP/WingFTPServer"

cat > "/Library/LaunchDaemons/WingFTPServer.plist" <<-EOF
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
	<dict>
		<key>Label</key>
		<string>WingFTPServer</string>
		<key>ProgramArguments</key>
		<array>
		<string>$WING_HOME/wftpserver</string>
		</array>
		<key>WorkingDirectory</key>
		<string>$WING_HOME</string>
		<key>RunAtLoad</key>
		<true/>
		<key>KeepAlive</key>
		<false/>
	</dict>
</plist>

EOF

chown root:wheel /Library/LaunchDaemons/WingFTPServer.plist
launchctl load -w /Library/LaunchDaemons/WingFTPServer.plist



cat > "$STARTUP_WFTP/StartupParameters.plist" <<-EOF
{
    Description = "Wing FTP Server";
    Provides = ("WingFTPServer");
    Requires = ("Disks","Network","Resolver");
    OrderPreference = "Last";
    Messages = 
    {
       start = "Starting Wing FTP Server";
       stop = "Stopping Wing FTP Server";
       restart = "Restarting Wing FTP Server";
    };
}

EOF

cat > "$STARTUP_WFTP/WingFTPServer" <<-EOF
#!/bin/sh
# Startup script for Wing FTP Server

. /etc/rc.common

StartService ()
{
    ConsoleMessage "Starting Wing FTP Server..."
    #exec $WING_HOME/wftpserver
    cd $WING_HOME
    ulimit -n 10240
    ./wftpserver & 1>/dev/null 2>&1
    echo "Wing FTP Server Started."
}

StopService ()
{
    ConsoleMessage "Stopping Wing FTP Server..."
    WFTP_PID=\`ps -ef | grep "\\.\\/wftpserver" | grep -v grep | awk '{print \$2}'\`
    if [ ! -z "\$WFTP_PID" ]; then
       kill -9 \$WFTP_PID & 1>/dev/null 2>&1
    fi
    echo "Wing FTP Server Stopped."
}

RestartService ()
{
    ConsoleMessage "Restarting Wing FTP Server..."
    StopService
    StartService
}

RunService "\$1"

EOF



echo ""
echo "Wing FTP Server has been installed successfully!"
echo "You can manage your server at http://YourIP:$adminport via a web browser."

alert "Do you want to start Wing FTP Server now?"
if [ "$?" -eq "0" ]
then
	cd $WING_HOME
	./wftpserver & 1>/dev/null 2>&1
	AdminUrl=`echo "http://127.0.0.1:$adminport" | tr -d ' ' `
	open $AdminUrl 1>/dev/null 2>&1
fi
