#!/bin/bash -i
#
# ZigzagDownLoader (ZDL)
# 
# This program is free software: you can redistribute it and/or modify it 
# under the terms of the GNU General Public License as published 
# by the Free Software Foundation; either version 3 of the License, 
# or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, 
# but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 
# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License 
# along with this program. If not, see http://www.gnu.org/licenses/. 
# 
# Copyright (C) 2011: Gianluca Zoni (zoninoz) <zoninoz@inventati.org>
# 
# For information or to collaborate on the project:
# https://savannah.nongnu.org/projects/zdl
# 
# Gianluca Zoni (author)
# http://inventati.org/zoninoz
# zoninoz@inventati.org
#

path_usr="/usr/local/share/zdl"

source $path_usr/ui/widgets.sh
source $path_usr/ui/ui.sh

source $path_usr/docs/help.sh
source $path_usr/config.sh
source $path_usr/config_manager.sh

source $path_usr/libs/core.sh
source $path_usr/libs/downloader_manager.sh
source $path_usr/libs/DLstdout_parser.sh
source $path_usr/libs/utils.sh
source $path_usr/libs/extension_utils.sh
source $path_usr/libs/login.sh
source $path_usr/libs/ip_changer.sh
source $path_usr/libs/log.sh
source $path_usr/libs/post_processor.sh


function update_updater {
    ## "...-mirror..." è quello principale (veloce)
    URL_ROOT="http://download-mirror.savannah.gnu.org/releases/zdl/"
    header_box "Aggiornamento automatico di $name_prog"

    [ ! -f $path_conf/version ] &&
	echo "0" >"$path_conf/version"
    
    remote_version=$(wget -qO- "${URL_ROOT}version")
    [[ ! "$remote_version" =~ ^([0-9]+)$ ]] &&
	remote_version=0
    
    local_version=$(cat "$path_conf/version")
    [[ ! "$local_version" =~ ^(-1|[0-9]+)$ ]] &&
	local_version='-1'

    if (( $local_version<$remote_version ))
    then
	#### aggiornamento versione da URL_ROOT
	echo "$remote_version" >$path_conf/version

	mkdir -p "$path_tmp"
	cd "$path_tmp"
	rm -fr *.gz *.sig "$prog" 2>/dev/null
	
	print_c 1 "Download in corso: attendere..."
	
	#### dal repo git: 
	# wget "http://git.savannah.gnu.org/cgit/zdl.git/snapshot/zdl-1.0.tar.gz" -q
	#
	#### dal mirror principale (veloce):

	#wget "$URL_ROOT" -r -l 1 -A gz -np -nd -q
	wget -q "http://download-mirror.savannah.gnu.org/releases/zdl/zdl-2.0.tar.gz"
	wget -q "http://download-mirror.savannah.gnu.org/releases/zdl/zdl-2.0.tar.gz.sig"
	package=$(ls *.tar.gz)
	print_c 1 "Aggiornamento di $PROG con $package"
	tar -xzf "$package"
	mv "${package%.tar.gz}" $prog

	## manutenzione: ##############
	# cp -r $HOME/zdl-git/code $prog
	cd $prog

	source updater.sh
	update

    else
	print_c 1 "$PROG è già alla versione più recente\n"
    fi
}

## controllo dipendenze (da implementare)
if [ -z "$nodejs" ]
then
    print_c 4 "${name_prog}:"
    print_c 3 "Manca una dipendenza (necessaria per alcune estensioni dei servizi): nodejs"
    pause
fi

args=( "$@" )

tags=( $(ps ax |head -n1) )
for ((i=0; i<${#tags[*]}; i++))
do
    j=$(( $i+1 ))
    [ "${tags[i]}" == "PID" ] && ps_ax_pid="\$$j"
    [ "${tags[i]}" == "TTY" ] && ps_ax_tty="\$$j"
done

#### è una pipe?
# stdin="$(ls -l /dev/fd/0)"
# stdin="${stdin/*-> /}"
# if [ "${stdin}" != "${stdin//'pipe:['}" ]
if [ -p /dev/fd/0 ]
then    
    pipe=$(cat /dev/fd/0)
    exec 0<$(echo /dev/$(ps ax| grep ^[\ ]*$$ | awk "{print $ps_ax_tty}"))
    
    for pipezed in $pipe
    do
	args[${#args[*]}]="$pipezed"
    done
    unset pipe
fi

max_args=$(( ${#args[*]}-1 ))

if [[ "${args[*]}" =~ \-[a-zA-Z0-9]{2} ]]
then
    for ((i=0; i<=$max_args; i++))
    do
	if [[ "${args[i]}" =~ ^-[a-zA-Z0-9]+$ ]] &&
	       [[ "${args[i]}" =~ m([0-9]+) ]]
	then
	    args[i]="${args[i]//m${BASH_REMATCH[1]}}"
	    [ "${args[i]}" == '-' ] &&
		unset args[i]
	    
	    args[++max_args]="-m"
	    args[++max_args]="${BASH_REMATCH[1]}"
	fi

	if [[ "${args[i]}" =~ ^-[a-zA-Z0-9]{2}$ ]]
	then
	    for ((j=1; j<${#args[i]}; j++))
	    do
	        args[++max_args]="-${args[i]:$j:1}"
	    done
	    unset args[i]
	fi
    done
fi



if [ "${args[*]}" == "${args[*]//--silent}" ] &&
       [ "${args[*]}" == "${args[*]//--stream}" ]
then
    for ((i=0; i<=$max_args; i++))
    do
	if [ -d "${args[i]}" ]
	then
	    BASE_DIR="$PWD/"
	    cd "${args[i]}"
	    unset args[i]
	fi
    done
fi

if [ "${args[*]}" != "${args[*]//--clean}" ]
then
    for ((i=0; i<=$max_args; i++))
    do
	if [ "${args[i]}" == '--clean' ]
	then 
	    unset args[i]
	    rm -r ".zdl_tmp"/* 2>/dev/null && 
		init_msg+="$(sprint_c 1 "File temporanei cancellati\n")" ||            
		    init_msg+="$(sprint_c 3 "Pulizia file temporanei non effettuata (file inesistenti)\n")"
	fi
    done
fi


#### MAIN
init


if [[ "${args[*]}" =~ \-\-url=[^\ ]+ ]]
then
    for ((i=0; i<=$max_args; i++))
    do
	if [[ "${args[i]}" =~ ^(--url=[^\ ]+)$ ]]
	then
	    url_regex=$(sed -r 's|--url=["]*(.+)["]*$|\1|g' <<< "${args[i]}")
	    unset args[i]
	fi
    done
fi

if [[ "${args[*]}" =~ \-\-no\-url=[^\ ]+ ]]
then
    for ((i=0; i<=$max_args; i++))
    do
	if [[ "${args[i]}" =~ ^(--no-url=[^\ ]+)$ ]]
	then
	    no_url_regex=$(sed -r 's|--no-url=["]*(.+)["]*$|\1|g' <<< "${args[i]}")
	    unset args[i]
	fi
    done
fi

if [[ "${args[*]}" =~ \-\-scrape-url=[^\ ]+ ]]
then
    for ((i=0; i<=$max_args; i++))
    do
	if [[ "${args[i]}" =~ ^(--scrape-url=[^\ ]+)$ ]]
	then
	    url_page=$(sed -r 's|--scrape-url=["]*(.+)["]*$|\1|g' <<< "${args[i]}")
	    scrape_url "$url_page"
	    unset args[i]
	fi
    done
fi


if [ "${args[*]}" != "${args[*]//--scrape-url}" ]
then
    for ((i=0; i<=$max_args; i++))
    do
	if [ "${args[i]}" == "--scrape-url" ]
	then
	    scrapeURL=true	    
	    unset args[i]
	fi
    done
fi

if [ "${args[*]}" != "${args[*]//--list-extensions}" ]
then
    for ((i=0; i<=$max_args; i++))
    do
	if [ "${args[i]}" == "--list-extensions" ]
	then
	    unset args[i]
	    this_mode=list
	    services_box
	    xterm_stop force
	    exit
	fi
    done
fi

if [[ "${args[*]}" =~ \-\-(mg|nano|mcedit|vi|vim|emacs|emacs-nw|jed|zile|jupp) ]]
then
    for ((i=0; i<=$max_args; i++))
    do
	if [[ "${args[i]}" =~ ^\-\-(mg|nano|mcedit|vi|vim|emacs|emacs-nw|jed|zile|jupp)$ ]]
	then
	    [[ $(command -v "${BASH_REMATCH[1]//-*}" 2>/dev/null) ]] && editor="${BASH_REMATCH[1]//-/ -}"
	    unset args[i]
	    from_editor=true
	fi
    done
fi

if [[ "${args[*]}" =~ (--editor|-e) ]]
then
    for ((i=0; i<=$max_args; i++))
    do
	if [[ "${args[i]}" =~ ^(--editor|-e)$ ]]
	then
	    unset args[i]
	    from_editor=true
	fi
    done
fi

if [ "${args[*]}" != "${args[*]//--silent}" ]
then
    for ((i=0; i<=$max_args; i++))
    do
	if [ "${args[i]}" == "--silent" ]
	then
	    unset args[i]
	    this_mode="daemon"
	    ## this_tty= importato da zdl --daemon
	    sleeping_pause=5

	    if [ "$(urldecode ${args[i+1]})" == "$PWD" ]
	    then
		unset args[i+1]
	    fi
	fi
    done
fi


## conkeror
if [ "${args[*]}" != "${args[*]//--zigzag-xterm}" ]
then
    if [ "$this_mode" != "daemon" ]
    then 
	if [ -z "$DISPLAY" ]
	then
	    export DISPLAY=":0"
	fi

	url="${args[*]%'--zigzag-xterm'*}"
	parameters="${args[*]#*'--zigzag-xterm'}"
	parameters="${parameters%'--cwd'*}"

	if [ -e "/cygdrive" ]
	then
	    dest_dir="${args[*]#*'--cwd'}"
	    dest_dir=$(cygpath -u "$dest_dir")
	    [ -n "$dest_dir" ] && cd "$dest_dir"
	    $prog "$url" $parameters --stop
	else
	    xterm -tn "xterm-256color"                                                                      \
		  -fa "XTerm*faceName: xft:Dejavu Sans Mono:pixelsize=12"                                   \
		  +bdc -fg grey -bg black -title "ZigzagDownLoader in $PWD"                                 \
		  -e "/bin/bash -i -c \"export pid_prog=\$$ ; zdl $parameters \\\"$url\\\" --stop \"" &
	fi
	exit
    else
	unset args
    fi
fi


if [ "${args[*]}" != "${args[*]//--stream}" ]
then
    for ((i=0; i<=$max_args; i++)) 
    do
	if [ "${args[i]}" == "--stream" ]
	then 
	## zdl --stream [URL] [FNAME] [FOLDER] [CFILE] [COOKIE] [REFERER]
	## zdl --stream [URL] [FNAME] --noXterm
	    if [ -z "$DISPLAY" ]
	    then
		export DISPLAY=":0"
	    fi
	    url_in="$2"
	    url_in="${url_in// /20%}"	    
	    test_dir_3="$3"
	    test_dir_4="$4"
	    if [ -e "/cygdrive" ]
	    then
		test_dir_3=$(cygpath -u "$test_dir_3")
		test_dir_4=$(cygpath -u "$test_dir_4")
	    fi 

	    if [ ! -d "$test_dir_3" ]
	    then
		file_in="$test_dir_3"
		if [ "$test_dir_4" != "--noXterm" ] &&
		       [ -d "$test_dir_4" ]
		then
		    directory="$test_dir_4"
		fi
	    else
		directory="$test_dir_3"
		unset file_in
	    fi

	    if [ "$file_in" != "${file_in//'/'/}" ]
	    then
		if [ -z "$directory" ]
		then
		    directory="${file_in%/*}"
		fi
		file_in="${file_in##*/}"
	    fi
	    file_in="${file_in// /_}"
	    file_in="${file_in##*/}"
	    file_in="${file_in::240}"
	    cfile="$5"
	    cookie="$6"
	    referer="$7"

	    if [ "$url_in" != "${url_in//nowvideo.}" ] &&
		   [ ! -e "/cygdrive" ]
	    then
		referer="$6"
		ext="${file_in##*.}"
		file_in2=$(wget "$referer" -qO- | grep "&amp;title=")
		file_in2="${file_in2#*'&amp;title='}"
		file_in2="${file_in2::240}"
		[ -n "$file_in2" ] &&
		    file_in2="${file_in2// /_}" &&
		    file_in="${file_in2%%\"*}.$ext"
	    fi

	    cd "$directory"
	    mkdir -p "${path_tmp}"
	    
	    if [ -e "$cfile" ]
	    then
		cat "$cfile" >> "$path_tmp/flashgot_cfile.zdl"
	    fi
	    echo -e "$cookie" > "$path_tmp/flashgot_cookie.zdl"

	    url_in="${url_in%'#20%'}"
	    echo "$url_in" > "${path_tmp}/filename_${file_in}.txt"
	    
	    if [ "$4" == "--noXterm" ] ||
		   [ -e "/cygdrive" ]
	    then
		export pid_prog=$$
		if ! check_instance_prog
		then
		    links_loop + "$url_in"
		    xterm_stop=true
		    links="$url_in"
		    redirect_links
		else
		    $prog "$url_in" $stream_params --stop
		fi
	    else
		xterm -tn "xterm-256color"                                                                          \
		      -fa "XTerm*faceName: xft:Dejavu Sans Mono:pixelsize=12"                                       \
		      +bdc -fg grey -bg black -title "ZigzagDownLoader in $PWD"                                     \
		      -e "/bin/bash -i -c \"export pid_prog=\$$ ; $prog \\\"$url_in\\\" $stream_params --stop\"" &
	    fi
	    exit
	fi
    done 
fi

## --stop deve precedere --mp3|--flac
if [ "${args[*]}" != "${args[*]//--stop}" ]
then
    for ((i=0; i<=$max_args; i++))
    do
	if [ "${args[i]}" == "--stop" ]
	then 
	    unset args[i]
	    xterm_stop=true
	fi
    done
fi


if [[ "${args[*]}" =~ (--mp3|--flac) ]]
then
    for ((i=0; i<=$max_args; i++))
    do
	if [[ "${args[i]}" =~ ^(--mp3|--flac)$ ]]
	then 
	    if [ -z "$(command -v ffmpeg 2>/dev/null)$(command -v avconv 2>/dev/null)" ]
	    then
		print_c 3 "La funzione di conversione in formato dipende da ffmpeg o da avconv, non trovati"
		exit
	    fi
	    format=${args[i]##*-}
	    unset args[i]
	    print_out="scaricati_da_zdl.txt"
	    unset args[i]
	fi
    done
fi


if [ "${args[*]}" != "${args[*]//--daemon}" ] ||
       [ "${args[*]}" != "${args[*]//-d}" ]
then
    for ((i=0; i<=$max_args; i++))
    do
	if [ "${args[i]}" == "--daemon" ] ||
	       [ "${args[i]}" == "-d" ]
	then
	    unset args[i]
	    already_clean=true
	    if check_instance_daemon
	    then
		mkdir -p "$path_tmp"
		export this_tty
		this_mode=stdout
		start_mode_in_tty "$this_mode" "$this_tty"
		
		date +%s >"$path_tmp"/.date_daemon

		nohup /bin/bash $prog ${args[*]} --silent "$PWD" &>/dev/null &
		
		print_c 4 "${name_prog}:"
		print_c 1 "Avviato in modalità demone in $PWD\n"
		print_c 4 "Puoi controllarlo con: ${Color_Off}$prog -i \"$PWD\"\n"
		[ -n "$xterm_stop" ] && xterm_stop
		exit 0

	    else
		start_mode_in_tty stdout "$this_tty"
		
		print_c 4 "${name_prog}:"
		print_c 3 "Esiste già un'istanza attiva della modalità demone in $PWD\n"
		print_c 4 "Puoi controllarlo con: ${Color_Off}$prog -i \"$PWD\"\n"

		this_mode=daemon
	    fi
	fi
    done
fi

export pid_prog=$$

if [ "${args[*]}" != "${args[*]//--help}" ] ||
       [ "${args[*]}" != "${args[*]//-h}" ]
then
    for ((i=0; i<=$max_args; i++))
    do
	if [ "${args[i]}" == "--help" ] ||
	       [ "${args[i]}" == "-h" ]
	then 
	    unset args[i]
	    usage
	fi
    done
fi


if [ "${args[*]}" != "${args[*]//--configure}" ] ||
       [ "${args[*]}" != "${args[*]//-c}" ]
then
    for ((i=0; i<=$max_args; i++))
    do
	if [[ "${args[i]}" =~ ^(\-\-configure|\-c)$ ]]
	then
	    unset args[i]
	    configure
	fi
    done
fi


if [ "${args[*]}" != "${args[*]//--interactive}" ] ||
       [ "${args[*]}" != "${args[*]//-i}" ]
then
    for ((i=0; i<=$max_args; i++))
    do
	if [ "${args[i]}" == '--interactive' ] ||
	       [ "${args[i]}" == '-i' ]
	then 
	    unset args[i]
	    interactive
	fi
    done
fi
## se non è modalità interattiva, allora sono validi i comandi "standard"
bindings


if [[ "${args[*]}" =~ (--lite|-l) ]]
then
    for ((i=0; i<=$max_args; i++))
    do
	if [[ "${args[i]}" =~ ^(--lite|-l)$ ]]
	then
	    this_mode=lite
	    lite_mode=true
	    unset args[i]
	fi
    done
fi





###
## change_mode di avvio: dopo list-extensions, lite, daemon, interactive, configure
## (tutte le modalità output che assegnano un valore a $this_mode)
###
start_mode_in_tty "$this_mode" "$this_tty"





##########
header_z
##########


if [ "${args[*]}" != "${args[*]//--update}" ] ||
       [ "${args[*]}" != "${args[*]//-u}" ]
then
    for ((i=0; i<=$max_args; i++))
    do
	if [ "${args[i]}" == '--force' ] ||
	       [ "${args[i]}" == '-f' ]
	then
	    unset args[i]
	    echo '-1' >"$path_conf/version"
	fi
    done
    for ((i=0; i<=$max_args; i++))
    do
	if [ "${args[i]}" == '--update' ] ||
	       [ "${args[i]}" == '-u' ]
	then
	    unset args[i]
	    update_updater
	fi
    done
    
elif [ "$autoupdate" == "enabled" ] &&
	 [ "${args[*]}" == "${args[*]//--interactive}" ] &&
	 [ "${args[*]}" == "${args[*]//-i}" ]
then
    for ((i=0; i<=$max_args; i++))
    do
	if [ "${args[i]}" == '--force' ] ||
	       [ "${args[i]}" == '-f' ]
	then
	    unset args[i]
	    echo '-1' >"$path_conf/version"
	fi
    done
    update_updater
fi

if [ "${args[*]}" != "${args[*]//--reconnect}" ]
then
    for ((i=0; i<=$max_args; i++))
    do
	if [ "${args[i]}" == "--reconnect" ]
	then
	    unset args[i]
	    reconnect_sh=true
	fi
    done
fi

## -T | --torrent-file=
if [[ "${args[*]}" =~ \-(T|\-torrent-file=) ]]
then
    for ((i=0; i<=$max_args; i++))
    do
	if [ "${args[i]}" == "-T" ]
	then
	    if [[ "${args[i+1]}" =~ (^[^-]+.*) ]]
	    then
		ftorrent="$BASE_DIR${BASH_REMATCH[1]}"
		if [ -f "${ftorrent}" ]
		then
		    [ "${ftorrent}" == "${ftorrent%.torrent}" ] &&
			mv "${ftorrent}" "${ftorrent}.torrent"
		    links_loop + "${ftorrent%.torrent}.torrent"
		fi	
		unset args[i+1]
	    fi
	    unset args[i] 
	fi
	
	if [[ "${args[i]}" =~ ^\-\-torrent-file=(.+)$ ]]
	then
	    ftorrent="$BASE_DIR${BASH_REMATCH[1]}"
	    if [ -f "${ftorrent}" ]
	    then
		[ "${ftorrent}" == "${ftorrent%.torrent}" ] &&
		    mv "${ftorrent}" "${ftorrent}.torrent"
		links_loop + "${ftorrent%.torrent}.torrent"
	    fi	
	    unset args[i]
	fi
	
    done
    
fi

## --(tcp|udp)-port=
if [[ "${args[*]}" =~ \-\-(tcp|udp)\-port= ]]
then
    for ((i=0; i<=$max_args; i++))
    do
	if [[ "${args[i]}" =~ ^\-\-(tcp|udp)-port=([0-9]+)$ ]]
	then
	    eval ${BASH_REMATCH[1]}_port="${BASH_REMATCH[2]}"
	    unset args[i]
	fi
    done
fi


if [[ "${args[*]}" =~ \-(m|\-multi=) ]]
then
    for ((i=0; i<=$max_args; i++))
    do
	if [ "${args[i]}" == "-m" ]
	then
	    if [[ "${args[i+1]}" =~ ^([0-9]+)$ ]]
	    then
		unset num_dl
		num_dl="${BASH_REMATCH[1]}"
		echo $num_dl >"$path_tmp/dl-mode"
		unset args[i+1]
	    fi
	    unset args[i]
	fi
	
	if [[ "${args[i]}" =~ ^\-\-multi=([0-9]+)$ ]]
	then
	    num_dl="${BASH_REMATCH[1]}"
	    echo $num_dl >"$path_tmp/dl-mode"
	    unset args[i]
	fi

    done
fi

if [ "${args[*]}" != "${args[*]//--ip}" ]
then
    for ((i=0; i<=$max_args; i++))
    do
	if [ "${args[i]}" == '--ip' ]
	then 
	    unset args[i]
	    my_ip
	fi
    done
fi

if [ "${args[*]}" != "${args[*]//--login}" ]
then
    for ((i=0; i<=$max_args; i++))
    do
	if [ "${args[i]}" == '--login' ]
	then 
	    unset args[i]
	    login=1
	fi
    done
fi


if [[ "${args[*]}" =~ '--'(wget|aria2|axel) ]]
then
    for ((i=0; i<=$max_args; i++))
    do
	if [[ "${args[i]}" =~ ^'--'(aria2|axel|wget)$ ]]
	then 
	    unset args[i]
	    	    
	    set_downloader $(tr [:lower:] [:upper:] <<< ${BASH_REMATCH[1]:0:1})${BASH_REMATCH[1]:1}
	fi
    done
fi


if [ "${args[*]}" != "${args[*]//--out=}" ]
then
    for ((i=0; i<=$max_args; i++))
    do
	if [ "${args[i]}" != "${args[i]#'--out='}" ]
	then
	    cmd_test=$(awk '{print $1}' <<< ${args[i]#'--out='} | tr -d \")
	    
	    if command -v $cmd_test &>/dev/null
	    then
		pipe_out_str="${args[i]#'--out='}"
		pipe_out=( ${pipe_out_str#\"} )

	    else
		file_output=scaricati_da_zdl.txt
		print_out="${args[i]#'--out='}"

		if [ -e "$print_out" ] 
		then
		    init_msg+="$(sprint_c 3 "Esiste già un file con lo stesso nome di ${print_out}\n")"
		    print_out="$file_output"
		elif [ -z "$print_out" ]
		then
		    print_out="$file_output"
		fi
		init_msg+="$(sprint_c 1 "La lista dei file verrà salvata in $print_out\n(puoi anche usarla per comunicare i file in scaricamento a un altro programma)\n")"
		touch "$print_out"
	    fi
	    unset args[i]
	fi
    done
fi

if [ "${args[*]}" != "${args[*]//--proxy}" ]
then
    for ((i=0; i<=$max_args; i++))
    do
	if [ "${args[i]}" != "${args[i]#'--proxy'}" ]
	then
	    if [ "${args[i]}" == '--proxy' ]
	    then
		update_proxy=true
		unset args[i]
		break

	    elif [ "${args[i]}" == '--proxy=t' ]
	    then
		proxy_types[${#proxy_types[*]}]="Transparent"
		update_proxy=true

	    elif [ "${args[i]}" == '--proxy=a' ]
	    then
		proxy_types[${#proxy_types[*]}]="Anonymous"
		update_proxy=true

	    elif [ "${args[i]}" == '--proxy=e' ]
	    then
		proxy_types[${#proxy_types[*]}]="Elite"
		update_proxy=true

	    elif [ "${args[i]}" != "${args[i]%'='*}" ]
	    then
		proxy="${args[i]#'--proxy='}"

		if [ -z "${proxy//[0-9.:]}" ]
		then
		    export http_proxy=$proxy
		    defined_proxy=$proxy
		    print_c 1 "Proxy attivo: $http_proxy\n"
		    update_defined_proxy=true
		    unset update_proxy
		else
		    print_c 3 "${args[i]}: argomento non valido\n\n"
		    usage
		fi
	    else
		print_c 3 "${args[i]}: argomento non valido\n\n"
		usage
	    fi
	    unset args[i]
	fi
    done
fi

if [[ "${args[*]}" =~ (-r|--resume) ]]
then
    for ((i=0; i<=$max_args; i++))
    do
	if [[ "${args[i]}" =~ ^(-r|--resume)$ ]]
	then 
	    unset args[i]
	    resume=enabled
	fi
    done
fi

if [[ "${args[*]}" =~ \-\-no-file=[^\ ]+ ]]
then
    for ((i=0; i<=$max_args; i++))
    do
	if [[ "${args[i]}" =~ ^(--no-file=[^\ ]+)$ ]]
	then
	    no_file_regex=$(sed -r 's;--no-file=["]*(.+)["]*$;\1;g' <<< "${args[i]}")
	    unset args[i]
	fi
    done
fi

if [[ "${args[*]}" =~ \-\-file=[^\ ]+ ]]
then
    for ((i=0; i<=$max_args; i++))
    do
	if [[ "${args[i]}" =~ ^(--file=[^\ ]+)$ ]]
	then
	    file_regex=$(sed -r 's;--file=["]*(.+)["]*$;\1;g' <<< "${args[i]}")
	    unset args[i]
	fi
    done
fi

if [[ "${args[*]}" =~ \-\-no-rev ]]
then
    for ((i=0; i<=$max_args; i++))
    do
	if [[ "${args[i]}" =~ ^(--no-rev)$ ]]
	then
	    no_file_regex='\.rev$'
	    unset args[i]
	fi
    done
fi

if [[ "${args[*]}" =~ \-\-no-sub ]]
then
    for ((i=0; i<=$max_args; i++))
    do
	if [[ "${args[i]}" =~ ^(--no-sub)$ ]]
	then
	    no_file_regex='[Ss]{1}[Uu]{1}[Bb]{1}'
	    unset args[i]
	fi
    done
fi


if [[ "${args[*]}" =~ \-\-no-complete ]]
then
    for ((i=0; i<=$max_args; i++))
    do
	if [[ "${args[i]}" =~ ^(--no-complete)$ ]]
	then
	    no_complete=true
	    unset args[i]
	fi
    done
fi


for ((i=0; i<=$max_args; i++))
do
    if [ "${args[i]}" != "${args[i]#-}" ]
    then
	print_c 3 "${args[i]}: argomento non valido\n\n"
	usage
    fi
done

if [ -n "${args[*]}" ]
then
    COOKIE="$path_tmp/flashgot_cfile.zdl"
    for ((i=0; i<=$max_args; i++))
    do
	if [ -f "${BASE_DIR}${args[i]}" ]
	then
	    if [ "${args[i]}" != "${args[i]%.dlc}" ]
	    then
		add_container $(cat "${BASE_DIR}${args[i]}") ## container_file

	    elif [ "${args[i]}" != "${args[i]%.torrent}" ]
	    then
		links_loop + "${BASE_DIR}${args[i]}"
		
	    else
		while read line
		do
		    sanitize_url "$line" >>"$path_tmp/sanitized_links"

		done <"${BASE_DIR}${args[i]}"

		grep_urls "$path_tmp/sanitized_links" >"$path_tmp"/links_loop.txt
	    fi
	    
	elif [ -n "${args[i]}" ]
	then
	    args[i]=$(sanitize_url "${args[i]}")
	    
	    if url "${args[i]}"
	    then
		if [ "$scrapeURL" == "true" ]
		then
		    scrape_url "${args[i]}"
		    
		else
		    if [ -z "$links" ]
		    then
			links="${args[i]}"
		    else
			links="${links}\n${args[i]}"
		    fi
		    start_file="$path_tmp/links_loop.txt"
		    links_loop + "${args[i]}"
		fi
	    else
		_log 12 "${args[i]}"
	    fi
	fi
    done

    if [ -f "$path_tmp"/links_loop.txt ]
    then 
	start_file="$path_tmp/links_loop.txt"
	clean_file "$start_file"
	echo >> links.txt 2>/dev/null
	date >> links.txt 2>/dev/null
	cat "$start_file" >> links.txt 2>/dev/null
	init_msg+="$(sprint_c 1 "L'elenco completo dei link è in links.txt\n")"

	if check_instance_prog &&
		[ -z "$from_editor" ]
	then
	    standard_box
	fi
    fi
fi


if [ -f "$path_tmp/downloader" ]
then
    downloader_in=$(cat "$path_tmp/downloader")
else
    echo $downloader_in > "$path_tmp/downloader"
fi

if [ -n "$from_editor" ]
then
    start_mode_in_tty editor "$this_tty"
    $editor "$path_tmp/links_loop.txt"
    this_mode=stdout
    start_mode_in_tty "$this_mode" "$this_tty"
    standard_box
fi


if [ -z "$start_file" ]
then
    start_file="$path_tmp/links_loop.txt"
    if check_instance_prog
    then
	echo "$pid_prog" > "$path_tmp/.pid.zdl"
    fi

    if [ -z "$from_editor" ] && [ "$this_mode" != "daemon" ]
    then
	binding=0
	standard_box
	## binding = {     0 -> while immissione URL
	##                 1 -> immissione URL terminata: premere invio
	##             unset -> break immissione URL                    }

	msg_end_input="Immissione URL terminata: premi invio per avviare i download"
	bind -x "\"\C-l\":\"\"" 2>/dev/null
	bind -x "\"\ex\":\"binding=1; print_c 2 '${msg_end_input}'\"" 2>/dev/null

	while [ -n "$binding" ]
	do
	    read -e link
	    [ "$binding" == 1 ] &&
		break
	    
	    if [ -n "${link// }" ]
	    then
		link=$(sanitize_url "$link")
		links_loop + "$link"
	    fi
	done
	unset link binding
	bind -x "\"\ex\":\"\"" 2>/dev/null
    fi
    
    if [ -f "$start_file" ]
    then
	clean_file "$start_file"
	echo >> links.txt 2>/dev/null
	date >> links.txt 2>/dev/null
	cat "$start_file" >> links.txt 2>/dev/null
	
    else
	rm -f "$path_tmp/rewriting"
    fi
fi

if ! check_instance_daemon &&
	[ "$this_mode" != "daemon" ] ||
	    ! check_instance_prog	    
then
    redirect_links 

else
    echo "$pid_prog" > "$path_tmp/.pid.zdl"
fi

[ -f "$path_tmp/downloader" ] ||    
    echo "$downloader_in" > "$path_tmp/downloader"

function main_loop {
    if [ "$this_mode" == "daemon" ] &&
	   [ ! -f "$start_file" ] &&
	   [ -z "$lite_mode" ]	
    then
    	start_file="$path_tmp/links_loop.txt"
   	sleep 10

    elif zero_dl
    then
	start_file="$path_tmp/links_loop.txt"
	sleep 5

    elif [ -f "$start_file" ] && [ -z "$zdl_exit" ]
    then
	clean_file "$start_file"
	
	#### do ... done < $start_file
	while read url_in
	do
	    if ! url "${url_in}"
	    then
		links_loop - "$url_in"
		_log 12 "$url_in"
	    fi
	    

	    if [ -n "$no_url_regex" ] && [[ "${url_in}" =~ $no_url_regex ]]
	    then
		links_loop - "$url_in"
		_log 15 "$url_in"
	    fi

	    if [ -n "$url_regex" ] && [[ ! "${url_in}" =~ $url_regex ]]
	    then
		links_loop - "$url_in"
		_log 16 "$url_in"
	    fi

	    if ! links_loop in "$url_in"
	    then
		break
	    fi

	    unset pid_in file_in url_in_file

	    if [ -f "$path_tmp/downloader" ]
	    then
		downloader_in=$(cat "$path_tmp/downloader")
	    fi

	    if ! check_in_loop
	    then
		[ -z "$url_in" ] && continue

		axel_parts=$axel_parts_conf
		url_in="${url_in## }"
		url_in="${url_in%% }"

		print_c 0
		header_box "Link da processare:"
		print_c 0 "$url_in\n"

		print_c 1 "Connessione in corso..."

		check_ip

		echo > "$path_tmp"/zdl.tmp > "$path_tmp"/zdl2.tmp

		## se ancora presenti redirezioni fantasma:
		kill -9 $(cat "$path_tmp"/pid_redirects) &>/dev/null
		rm -f "$path_tmp/redirect"
		###################

		## extensions
		if [ -d "$path_usr/extensions/" ]
		then
		    shopt -s nullglob
		    export LANG="$prog_lang"
		    export LANGUAGE="$prog_lang"

		    for srcfile in "$path_usr"/extensions/*.sh
		    do
			[ -f "$srcfile" ] &&
			    source "$srcfile"
		    done

		    export LANG="$user_lang"
		    export LANGUAGE="$user_language"
    		    shopt -u nullglob
		fi

####		check_dler_forcing
		
		## se ancora presenti redirezioni fantasma:
		kill -9 $(cat "$path_tmp"/pid_redirects) &>/dev/null
		rm -f "$path_tmp/redirect"
		###################

		if [ "$break_loop" == "true" ]
		then
		    unset break_loop
		    show_downloads
		    sleep 1
		    continue
		fi

		if [ -z "$file_in" ] || [ -z "$url_in_file" ]
		then
		 
		## streaming downloader
		    items=( $(ls "$path_tmp"/filename_* 2>/dev/null) )
		    for item in ${items[*]}
		    do
			url=$(cat "$item" 2>/dev/null)
			if [ "${url%% }" == "$url_in" ]
			then
			    item="${item// /_}"
			    file_in="${item#*filename_}"
			    file_in="${file_in%.txt}"
			    break
			fi
		    done

		## universal downloader
		    if [ -z "$file_in" ] && [ -z "$url_in_file" ]
		    then
			file_in="${url_in##*'/'}"
			file_in="${file_in%'?'*}"
			file_in="${file_in%%'&'*}"
		    fi
		    url_in_file="${url_in%% }"
		    url_in_file="${url_in_file## }"
		    
		fi

		sanitize_file_in

		if ! check_freespace
		then
		    break_loop="true"
		    zdl_exit="true" 
		fi

		if [ -z "$file_filtered" ]
		then
		    file_filter "$url_in"
		else
		    unset file_filtered
		fi

		if ! url "$url_in_file" && 
			[[ "$downloader_in" =~ (Aria2|Wget|Axel) ]] ||
			    [ "$break_loop" == "true" ]
		then
		    unset break_loop
		    show_downloads
		    sleep 1
		    continue
		fi

		#### DOWNLOAD ####
		if [ -z "$premium" ] &&                                                 
		       check_in_file &&                                                         
		       links_loop "in" "$url_in" 
		then
		    #
		    ## check in nuova posizione da testare: prima era più in alto
		    #
		    check_dler_forcing

		    if [[ "$downloader_in" =~ (RTMPDump|cURL) ]]
		    then
			print_c 4 "Streamer: $streamer\nPlaypath: $playpath\n"
		    else
			print_c 4 "URL del file: $url_in_file"
		    fi

		    if download
		    then
			print_c 1 "downloading --> $file_in ..."
		    fi		    
		    rm -f "$path_tmp/cookies.zdl"
		    unset no_newip
		    check_freespace
		fi

		newip_add_provider
		from_loop=true

		[ "$ch_dler" == "1" ] &&
		    downloader_in=$dler &&
		    unset ch_dler

		noproxy

		while true 
		do
		    pipe_files
		    show_downloads
		    if ! check_in_loop
		    then
			no_msg=true
			break
		    fi
		    sleeping "$sleeping_pause"
		done

		unset break_loop post_data not_available exceeded 
	    fi
	done < "$start_file"

	[ -z "$no_msg" ] && sleeping $sleeping_pause
	clean_file "$path_tmp"/links_loop.txt
	pipe_files

	if [ -f "$path_tmp/links_loop.txt" ]
	then
	    start_file="$path_tmp/links_loop.txt"
	fi

	[ -z "$no_msg" ] && show_downloads
	unset no_msg
    else 
	return 1
    fi
}


trap_sigint
if [ "$this_mode" == "daemon" ]
then
    while true
    do
	main_loop || break
    done
    
else
    if [ "$lite_mode" == true ] ||
	   [ "$this_mode" == lite ]
    then
	lite_mode=true
	this_mode=daemon
	start_mode_in_tty "lite" "${this_tty}" 
    fi
    
    while true
    do
	main_loop || break
    done 2>/dev/null &

    [ "$lite_mode" == true ] &&
	this_mode=lite
    
    loops_pid=$!
fi

if [ "$this_mode" != "daemon" ]
then
    stty -echo
    bindings
    while check_pid $loops_pid
    do
	if [ "$this_mode" == "lite" ]
	then
	    show_downloads_lite

	    read -e -n 1 -t 2 binding_in_loop

	else
	    read -e -n 1 -t 1 binding_in_loop
	fi
    done

    if [ "$this_mode" == "lite" ]
    then
	show_downloads_lite
    fi
fi

wait $loops_pid

trap_sigint
noproxy

separator-
print_c 1 "Download completato"
separator-

stty echo

if [ -n "${pipe_out[*]}" ] && [ "$pipe_done" != 1 ]
then
    data_stdout
    pipe_files
fi


post_process || exit 1

if [ "$zdl_exit" != "true" ]
then
    test_pid="$(cat "$path_tmp"/.pid.zdl 2>/dev/null)"

    [ "$test_pid" == "$pid_prog" ] &&
	rm -rf "$path_tmp"
    
else
    kill_downloads
fi

echo -e "\n\n"

if [ -f "$file_log" ]
then
    print_c 3 "In $PWD è presente un file che contiene un elenco di operazioni di $PROG terminate senza successo."
    print_c 0 "${BBlue}Per leggerlo, digita:${Color_Off}\n${Bold}cat $PWD/$file_log${Color_Off}\n\n"
fi


if [ "$xterm_stop" == "true" ]
then
    xterm_stop
fi

echo -en "\e[0m\e[J"




