#!/bin/bash

SOURCEPATH="*"
timeout --foreground 3600s inotifywait -m --exclude="node_modules|.git|cache|.*\.(sw([px]+)|new|~)|tmp$"  -r * -e CREATE,CLOSE_WRITE,DELETE --format "%w%f" --timefmt '%H%M%S' 2>/dev/null  | while read file
do
    WHITE='\033[1;37m';
    RED='\033[31m';
    GREEN='\033[0;32m';
    RESET='\e[m';
    NUM=0
    for SUBPATH in $file
    do
        NUM=$((NUM+1))
        printf "${WHITE}[$NUM] Path: $SUBPATH${RESET}\n"
        FILES=( $(find $SUBPATH -type f))

        NUMFILE=0
        PIDS=()
        find $SUBPATH -type f | while read FILE
        do
            NUMFILE=$((NUMFILE+1))
            printf "${WHITE}[${NUM}] Uploading $FILE${RESET}\n";
            ( [[ "$(curl \
                -m 600 \
                -q \
                -D - \
                -isSL \
                --user "user:password" \
                -T "$FILE"  \
                "https://sfcc-host-here/on/demandware.servlet/webdav/Sites/Cartridges/version1/$FILE"  | grep 'HTTP/1.1 2' )" != "" ]] )  &
            NEWPID=$!
            printf "${WHITE}[${NUM}] ${GREEN}Uploaded OK${RESET}\n"
            PIDS+=($NEWPID)

            if [ "${#PIDS[@]}" -gt "4" ]
            then
                printf "${WHITE}[${NUM}] Waiting processes: ${PIDS[*]}${RESET}"
                while [ "${#PIDS[@]}" -gt "4" ]
                do
                    printf "."
                    for i in "${PIDS[@]}"
                    do
                        #echo "Check status of upload $i"
                        kill -0 "$i" 2>/dev/null
                        if [ $? -ne 0 ]
                        then
                            $(wait $i)
                            RWAIT=$?
                            echo "RWAIT = $RWAIT"
                            if [[ "$RWAIT" == "1" ]]
                            then
                                echo "FAIL!"
                            fi
                            DELETE=("$i")
                            PIDS=("${PIDS[@]/$DELETE}")
                            PIDS=($PIDS)
                            #echo "Process ${PIDS[$i]} ended. remains ${PIDS[@]} - deleted ${DELETE[@]}"
                        fi
                    done
                    sleep 0.2s
                done
                printf "\n${RESET}"
            fi
        done
    done
done
