#!/bin/bash

# Copyright: 2023 Virtuozzo International GmbH

# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at

# http://www.apache.org/licenses/LICENSE-2.0

# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

[ -n "${VSFTPDLIB_VERSION:-}" ] && return 0;
VSFTPDLIB_VERSION="0.1";

include log output os;

PEM_KEY=/etc/vsftpd/vsftpd.pem
STATE="US"
CITY="Palo Alto"
ORG="Jelastic, Inc"
FTP_USERNAME="jelastic-ftp"
SHELLS_FILE="/etc/shells"
FTP_PROCESS_NAME="vsftpd"

function setvsFtpCert(){
        APPSERVER_USER_UID=$(id -u jelastic 2>/dev/null || echo 700 )
        [[ "x${COMPUTE_TYPE,,}" == "xstorage" ]] || {
            find $MOUNT_DIR -not -uid $APPSERVER_USER_UID -print0 | xargs -0 -n1000 -r chown -R $APPSERVER_USER_UID 2>/dev/null;
        }
        [ -d "/var/ftp/pub" ]  && rmdir "/var/ftp/pub/" >/dev/null 2>&1;
        if [ -f /usr/lib/systemd/system/vsftpd.service ]; then
            [ -f /etc/rc.d/init.d/vsftpd ] && rm -f /etc/rc.d/init.d/vsftpd;
        fi

        # ensure vsftpd service not running
        if pgrep "^$FTP_PROCESS_NAME$" ; then
            stopServiceSilent $FTP_PROCESS_NAME

            #perform double check and send KILL if process still alive
            pgrep "^$FTP_PROCESS_NAME$" && kill -9 $(pgrep "^$FTP_PROCESS_NAME$")
        fi

umask 77 ; echo "$COUNTRY
$STATE
$CITY
$ORG
$UNIT
$HOST
$EMAIL" |  openssl req -x509 -nodes -days 1826 -newkey rsa:2048 -keyout $PEM_KEY -out $PEM_KEY >/dev/null 2>&1;
        grep -q "/bin/false" "$SHELLS_FILE" || echo "/bin/false" >> $SHELLS_FILE ;
        getent passwd $FTP_USERNAME >/dev/null || /usr/sbin/adduser -o --uid $APPSERVER_USER_UID --home-dir $MOUNT_DIR --shell /bin/false $FTP_USERNAME 2>/dev/null;
        chown root:root /etc/vsftpd/ -R >/dev/null  2>&1

        if [ -f /usr/lib/systemd/system/vsftpd.service ]; then
            systemctl enable vsftpd.service >/dev/null  2>&1
        else
            /sbin/chkconfig --add vsftpd --level 345 2>&1 1>/dev/null
            /sbin/chkconfig  vsftpd on >/dev/null  2>&1
        fi

        startServiceSilent $FTP_PROCESS_NAME
        return 0
}
