#!/bin/bash
# info: add backup ftp host
# options: HOST USERNAME PASSWORD [PATH] [PORT]
#
# The function adds ftp host for system backups


#----------------------------------------------------------#
#                    Variable&Function                     #
#----------------------------------------------------------#

# Argument defenition
host=$1
ftp_user=$2
ftp_password=$3
ftp_path=${4-/backup}
ftp_port=${5-21}
A3='******'

# Includes
source $VESTA/func/main.sh
source $VESTA/conf/vesta.conf

# Defining ftp command function
ftpc() {
    ftp -p -n $host $ftp_port <<EOF
    quote USER $ftp_user
    quote PASS $ftp_password
    binary
    $1
    $2
    $3
    quit
EOF
}


#----------------------------------------------------------#
#                    Verifications                         #
#----------------------------------------------------------#

check_args '3' "$#" "HOST USERNAME PASSWORD [PATH] [PORT]"
validate_format 'host' 'ftp_user' 'ftp_password'


#----------------------------------------------------------#
#                       Action                             #
#----------------------------------------------------------#

# Checking network connection
fconn=$(ftpc)
ferror=$(echo $fconn |grep -i -e failed -e error -e "Can't" -e "not conn")
if [ ! -z "$ferror" ]; then
    echo "Error: can't login to ftp"
    log_event "$E_CONNECT" "$EVENT"
    exit $E_CONNECT
fi

# Checking write permissions
ftpc "mkdir $ftp_path" > /dev/null 2>&1
ftmpdir="$ftp_path/vst.bK76A9SUkt"
ftp_result=$(ftpc "mkdir $ftmpdir" "rm $ftmpdir"|grep -v Trying)
if [ ! -z "$ftp_result" ] ; then
    echo "$ftp_result"
    rm -rf $tmpdir
    echo "Error: can't create temp folder on the ftp"
    log_event "$E_FTP" "$EVENT"
    exit $E_FTP
fi

# Adding backup host
echo "HOST='$host'
USERNAME='$ftp_user'
PASSWORD='$ftp_password'
BPATH='$ftp_path'
PORT='$ftp_port'
TIME='$TIME'
DATE='$DATE'" > $VESTA/conf/ftp.backup.conf
chmod 660 $VESTA/conf/ftp.backup.conf


#----------------------------------------------------------#
#                       Vesta                              #
#----------------------------------------------------------#

# Update vesta.conf
if [ -z "$(grep LANGUAGE $VESTA/conf/vesta.conf)" ]; then
    echo "BACKUP_SYSTEM='ftp'" >> $VESTA/conf/vesta.conf
else
    bckp=$(echo "$BACKUP_SYSTEM,ftp" |\
        sed "s/,/\n/g"|\
        sort -r -u |\
        sed "/^$/d"|\
        sed ':a;N;$!ba;s/\n/,/g')
    sed -i "s/BACKUP_SYSTEM=.*/BACKUP_SYSTEM='$bckp'/g" $VESTA/conf/vesta.conf
fi

# Logging
log_event "$OK" "$EVENT"

exit
