#!/bin/bash
# Add the $HOSTDIR address in front of the sfs name
#URILIST="`echo "$LIST" | sed "s,^,$HOSTDIR/," | sed ':a;N;$!ba;s/\n/ /g'`"
#URILIST="`echo "$LIST" | sed "s,^,$HOSTDIR/," | tr '\n' ' '`"
URILIST="ftp://ftp.yandex.ru/ubuntu/ls-lR.gz"

# Set GUI variables up
TITLE="YAD wget downloader"                 # dialog title
ICON="gtk-save"                     # window icon (appears in launcher)
IMAGE="save48"                    # window image (appears in dialog)


# Select folder to download to:
#SAVEFOLDER=$(yad  --center --image="application-x-squashfs" --image-on-top --title="Select folder to download SFS modules" --file --height=600 --width=800 --text=" Select folder to download SFS modules to" )
#ret=$?
#[[ $ret -ne 0 ]] && exit 1

MAXDLS="5" # set maximum number of simultaneous downloads

# download file and extract progress, speed and ETA from wget
# we use sed regex for this
# source: http://ubuntuforums.org/showthread.php?t=306515&page=2&p=7455412#post7455412
# modified to work with different locales and decimal point conventions

download(){
#    cd "$SAVEFOLDER"
    wget -N --no-check-certificate "$1" 2>&1 | sed -u \
    "s/.* \([0-9]\+%\)\ \+\([0-9,.]\+.\) \(.*\)/$2:\1\n$2:# Скорость: \2\/сек., Время: \3/"
    RET_WGET="${PIPESTATUS[0]}"             # get return code of wget
    if [[ "$RET_WGET" = 0 ]]                # check return code for errors
      then
          echo "$2:100%"
          echo "$2:#Download completed."
      else
          case "$RET_WGET" in
            1) 
        	r="Generic error code." 
        	;;
	    2)
		r="Parse error—for instance, when parsing command-line options, the ‘.wgetrc’ or ‘.netrc’..." 
		;;
	    3)
		r="File I/O error." 
		;;
	    4)
		r="Network failure." 
		;;
	    5)
		r="SSL verification failure." 
		;;
	    6)
		r="Username/password authentication failure." ;;
	    7)
		r="Protocol errors." ;;
	    8)
		r="Server issued an error response." ;;
          esac
          echo "$2:#Ошибка. \n$r"
    fi
}


# compose list of bars for yad
for URI in $URILIST; do                     # iterate through all URIs
    FILENAME="${URI##*/}"                   # extract last field of URI as filename
#    YADBARS="$YADBARS --bar=$FILENAME:NORM" # add filename to the list of URIs
    YADBARS="$YADBARS --bar=:NORM" # add filename to the list of URIs
done
TEXT="             <b>Загрузка</b> $FILENAME:"        # dialog text

IFS=" "
COUNTER="1"
DYNAMIC_COUNTER="1"

# main
# iterate through all URIs, download them in the background and 
# pipe all output simultaneously to yad
# source: http://pastebin.com/yBL2wjaY

for URI in $URILIST; do
    if [[ "$DYNAMIC_COUNTER" = "$MAXDLS" ]] # only download n files at a time
      then
          download "$URI" "$COUNTER"        # if limit reached wait until wget complete
          DYNAMIC_COUNTER="1"               # before proceeding (by not sending download() to bg)
      else
          download "$URI" "$COUNTER" &      # pass URI and URI number to download()
          DYNAMIC_COUNTER="$[$DYNAMIC_COUNTER+1]"
    fi
    COUNTER="$[$COUNTER+1]"                 # increment counter
done | yad --center --multi-progress --auto-kill $YADBARS --title "$TITLE" \
--auto-close --text "$TEXT" --window-icon "$ICON" --image "$IMAGE"

# ↑ launch yad multi progress-bar window
