#!/bin/bash

ftpLog="/var/log/ftp"
ftpLocDir="/data/share_res/ftp"
ftpLock=$ftpLog/lock
#ftpOpts="--ignore-time -e -c -v"
ftpOpts="-e -c -v"

TargetsList=("home.home/OpenSCADA/LTS/SuSE/15" "/OpenSCADA/LTS/CentOs/8" "/OpenSCADA/LTS/Ubuntu/24.04" "/OpenSCADA/LTS/Ubuntu/22.04" "/OpenSCADA/LTS/Ubuntu/20.04" "/OpenSCADA/LTS/Ubuntu/18.04"
	    "/OpenSCADA/LTS/Live:/OpenSCADA/LTS/Live/new"
	    "/OpenSCADA/Work/SuSE/15" "/OpenSCADA/Work/CentOs/8" "/OpenSCADA/Work/Ubuntu/24.04" "/OpenSCADA/Work/Ubuntu/22.04" "/OpenSCADA/Work/Ubuntu/20.04" "/OpenSCADA/Work/Ubuntu/18.04"
	    "/OpenSCADA/Work/Live:/OpenSCADA/Work/Live/new"
	    "/Debian/12" "/Debian/11" "/Debian/10" "/Debian/9"
	    "pi.home/OpenSCADA/LTS/Raspbian" "/OpenSCADA/Work/Raspbian")

test -f $ftpLock && kill -0 "$(cat $ftpLock)" 2> /dev/null && echo "Syncing is going now!" && exit 0;
echo $$ > $ftpLock

#Moving the command line targets to the TargetsList for the force syncing
if test $# -gt 0; then
    iTarg=0
    unset TargetsList
    while test $# -gt 0; do
	TargetsList[iTarg]=$1
	shift
	iTarg=$(($iTarg + 1))
    done
    echo "Appending custom-force targets from the command line - ${TargetsList[*]}"
fi

#Processing the target list
iTarg=0
while test "x${TargetsList[iTarg]}" != "x"; do
    ftpServ_=`echo ${TargetsList[iTarg]} | sed -n "/^\([^/]*\).*$/s//\1/p"`
    ftpURI_to=`echo ${TargetsList[iTarg]} | sed -n "/^[^/]*.*:\(.*\)/s//\1/p"`
    if test -z "$ftpURI_to"; then
	ftpURI=`echo ${TargetsList[iTarg]} | sed -n "/^[^/]*\(.*\)$/s//\1/p"`
	ftpURI_to=$ftpURI
    else
	ftpURI=`echo ${TargetsList[iTarg]} | sed -n "/^[^/]*\(.*\):.*/s//\1/p"`
    fi

    if test -n "$ftpServ_"; then ftpServ=$ftpServ_; fi
    if test -n "$ftpServ"; then
	echo "Syncing the FTP resource for the target '${TargetsList[iTarg]}', where the server is '$ftpServ' and the URI is '$ftpURI' to the folder '$ftpLocDir$ftpURI_to'."
	echo "The log name = $(echo $ftpURI | tr '/' '_')"
	lftp $ftpServ -e "mirror $ftpOpts --log=$ftpLog/$ftpServ$(echo $ftpURI | tr '/' '_').log $ftpURI $ftpLocDir$ftpURI_to; quit" 2> /dev/null
    fi
    iTarg=$(($iTarg + 1))
done