#!/bin/bash

##################################################
# Mount file                                     #
# - /etc/vsftpd/vsftpd.conf                      #
# Mount dir                                      #
# - /var/lib/ftp, /home or other data_dir        #
# - LOG_DIR                                      #
# ENV                                            #
# - VSFTPD_OPTS                                  #
##################################################

set -euo pipefail
export LANG=en_US.UTF-8
trap Quit EXIT

PIDS=
GOT_SIGTERM=
LOG_DIR='/var/log/vsftpd'
ARGS="${VSFTPD_OPTS:-}"

function Print {
    local file=/dev/null
    [ '-f' = "$1" ] && file=$2 && shift && shift
    date +"[%F %T] $*" | tee -a $file
}

function Quit {
    Print killing vsftpd ...
    while :; do
        pkill -f rsync && Print killing vsftpd ... || break
        sleep 1
    done
    Print Container stopped.
    test -n "$GOT_SIGTERM"
}

function CreateFtpUser {
    local kv=
    local uid=
    local user=
    local userList=/etc/vsftpd/user_list
    Print Create ftp users ...
    : > $userList
    grep -q '^anonymous_enable *= *YES' /etc/vsftpd/vsftpd.conf && echo anonymous >> $userList
    for kv in $(env | grep '^FTP_USER_[0-9]\+='); do
        uid=$(echo $kv | cut -d= -f1 | cut -d_ -f3)
        user=$(echo $kv | cut -d= -f2- | cut -d: -f1)
        userPass=$(echo $kv | cut -d= -f2-)
        id $uid || adduser -D -s /sbin/nologin -u $uid $user
        echo "${userPass}" | chpasswd
        echo $user >> $userList
    done
}

function StartProc {
    Print Starting vsftpd ...
    vsftpd /etc/vsftpd/vsftpd.conf $ARGS /etc/vsftpd/vsftpd-sys.conf &
    PIDS="$PIDS $!"
    Print vsftpd started.
}

function Main {
    local pid=
    CreateFtpUser
    StartProc
    trap "GOT_SIGTERM=1; Print Got SIGTERM ..." SIGTERM
    while [ -z "$GOT_SIGTERM" ] && sleep 2; do
        for pid in $PIDS; do
            [ ! -e /proc/$pid ] && Print Unexpected error! && exit
        done
    done
}

# Start here
Main

