#!/bin/bash -i
#
# ZigzagProxy (ZPROXY)
# 
# 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) 2012
# Gianluca Zoni <zoninoz@inventati.org>
# 
# For information or to collaborate on the project:
# https://savannah.nongnu.org/projects/zproxy
# 
# Gianluca Zoni
# http://inventati.org/zoninoz
# zoninoz@inventati.org
#


#### CONFIG
# NB: se si usa "source" oppure "." prima dello script, ovviamente "$prog" è "/bin/bash", quindi è meglio scegliere un nome al posto di basename:
#prog=`basename $0`

prog="zproxy"
proxy_list_sources=(
    https://proxyscrape.com/free-proxy-list
    https://ip-adress.com/proxy_list/
    http://proxy-list.org/en/index.php
)

PROG=$(tr a-z A-Z <<< "$prog")
path_prog="$HOME/.$prog"
path_tmp="$path_prog"
mkdir -p "$path_prog"
#proxy_types=( Transparent )
credentials="$path_prog/.modem_credentials.txt"
max_waiting=40
    
url_update="http://git.savannah.nongnu.org/cgit/zproxy.git/snapshot/zproxy-1.0.tar.gz"

update=false
help=false
disable_proxy=false
transparent=false
anonymous=false
elite=false
reconnect=false
ip=false
cmds=()

user_agent="Mozilla/5.0 (X11; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0"
user_lang="$LANG"
user_language="$LANGUAGE"
prog_lang='en_US.UTF-8:en'

ip_server_url='http://indirizzo-ip.com/ip.php'
#firefox_profile_path=/tmp/zproxy
firefox_profile_path_bak=$HOME/.mozilla/firefox/zproxy

## testing:
# export LANG="$prog_lang"
# export LANGUAGE="$prog_lang"


if [[ "${LANGUAGE}${LANG}" =~ (it|IT) ]]
then
    msg[0]="Indirizzo IP:"
    msg[1]="Riconnessione del modem (cambio indirizzo IP)"
    msg[2]="Cambio indirizzo IP..."
    msg[3]="Funzione disattivata: non esiste il file di configurazione $credentials"
    msg[4]="Proxy non disponibili"
    msg[5]="Test velocità di download:"
    msg[6]="Velocità di download sufficiente usando il proxy" #" $http_proxy: ${num_speed[i]} KB/s"
    msg[7]="La massima velocità di download raggiunta usando il proxy è inferiore a quella minima richiesta"
    msg[8]="Massima velocità di download raggiunta usando il proxy"
    msg[9]="Proxy attivo:"
    msg[10]="Proxy non attivo\n"
    msg[11]="Attivazione proxy:"
    msg[12]="\nAggiorna proxy"
    msg[13]="Proxy attualmente non disponibile: proxy disattivato"
    msg[14]="Aggiornamento di $PROG ..."
    msg[15]="Installazione di $PROG in /usr/local/bin/ ..."
    msg[16]="Aggiornamento completato."
    msg[17]="Aggiornamento automatico non riuscito"
    msg[18]="Proxy disattivato\n"
    msg[19]="Lista di ricerca proxy"
    msg[20]="ZigzagProxy già aggiornato all'ultima versione\n"
    msg[21]="non esiste"
    
else
    msg[0]="IP address:"
    msg[1]="Reconnecting modem (changing IP address)"
    msg[2]="Changing IP address..."
    msg[3]="Function disabled: configuration file $credentials does not exist"
    msg[4]="Proxies not available"
    msg[5]="Speed test of downloading:"
    msg[6]="Sufficient download speed using proxy" #" $http_proxy: ${num_speed[i]} KB/s"
    msg[7]="The maximum download speed achieved using the proxy is less than the minimum required"
    msg[8]="Maximum download speed achieved using the proxy"
    msg[9]="Active proxy:"
    msg[10]="Proxy not active\n"
    msg[11]="Proxy activation:"
    msg[12]="\nUpdate proxy"
    msg[13]="Proxy currently unavailable: proxy disabled"
    msg[14]="Update of $PROG ..."
    msg[15]="Installing $PROG in /usr/local/bin/ ..."
    msg[16]="Update completed."
    msg[17]="Automatic update failed"
    msg[18]="Proxy disabled\n"
    msg[19]="Proxy search list"
    msg[20]="ZigzagProxy already updated to the latest version\n"
    msg[21]="does not exist"
fi


#### start layout

function init_colors {
	# Reset
    Color_Off='\e[0m'       # Text Reset
    
	# Regular Colors
    Black='\e[0;30m'        # Nero
    Red='\e[0;31m'          # Rosso
    Green='\e[0;32m'        # Verde
    Yellow='\e[0;33m'       # Giallo
    Blue='\e[0;34m'         # Blu
    Purple='\e[0;35m'       # Viola
    Cyan='\e[0;36m'         # Ciano
    White='\e[0;37m'        # Bianco
    
	# Bold
    BBlack='\e[1;30m'       # Nero
    BRed='\e[1;31m'         # Rosso
    BGreen='\e[1;32m'       # Verde
    BYellow='\e[1;33m'      # Giallo
    BBlue='\e[1;34m'        # Blu
    BPurple='\e[1;35m'      # Viola
    BCyan='\e[1;36m'        # Ciano
    BWhite='\e[1;37m'       # Bianco
    
	# Underline
    UBlack='\e[4;30m'       # Nero
    URed='\e[4;31m'         # Rosso
    UGreen='\e[4;32m'       # Verde
    UYellow='\e[4;33m'      # Giallo
    UBlue='\e[4;34m'        # Blu
    UPurple='\e[4;35m'      # Viola
    UCyan='\e[4;36m'        # Ciano
    UWhite='\e[4;37m'       # Bianco
    
	# Background
    On_Black='\e[40m'       # Nero
    On_Red='\e[41m'         # Rosso
    On_Green='\e[42m'       # Verde
    On_Yellow='\e[43m'      # Giallo
    On_Blue='\e[44m'        # Blu
    On_Purple='\e[45m'      # Purple
    On_Cyan='\e[46m'        # Ciano
    On_White='\e[47m'       # Bianco
    
	# High Intensty
    IBlack='\e[0;90m'       # Nero
    IRed='\e[0;91m'         # Rosso
    IGreen='\e[0;92m'       # Verde
    IYellow='\e[0;93m'      # Giallo
    IBlue='\e[0;94m'        # Blu
    IPurple='\e[0;95m'      # Viola
    ICyan='\e[0;96m'        # Ciano
    IWhite='\e[0;97m'       # Bianco
    
	# Bold High Intensty
    BIBlack='\e[1;90m'      # Nero
    BIRed='\e[1;91m'        # Rosso
    BIGreen='\e[1;92m'      # Verde
    BIYellow='\e[1;93m'     # Giallo
    BIBlue='\e[1;94m'       # Blu
    BIPurple='\e[1;95m'     # Viola
    BICyan='\e[1;96m'       # Ciano
    BIWhite='\e[1;97m'      # Bianco
    
	# High Intensty backgrounds
    On_IBlack='\e[0;100m'   # Nero
    On_IRed='\e[0;101m'     # Rosso
    On_IGreen='\e[0;102m'   # Verde
    On_IYellow='\e[0;103m'  # Giallo
    On_IBlue='\e[0;104m'    # Blu
    On_IPurple='\e[10;95m'  # Viola
    On_ICyan='\e[0;106m'    # Ciano
    On_IWhite='\e[0;107m'   # Bianco
}

function print_c {
    case "$1" in
	1)
	    echo -ne '\e[1;32m' #verde
	    ;;
	2)
	    echo -ne '\e[1;33m' #giallo
	    ;;	
	3)
	    echo -ne '\e[1;31m' #rosso
	    ;;	
	4)
	    echo -ne "$BBlue"
    esac
    echo -ne "$2\n"
    echo -ne "${Color_Off}"
}

function separator {
    #COLUMNS=$( tput cols ) 2>/dev/null
    if [ -z "$COLUMNS" ]
    then 
	COLUMNS=50
    fi

    echo -ne "${BBlue}"
    for column in $(seq 1 $COLUMNS)
    do
	echo -ne "$1"
    done
    #\e[1;34m

    echo -ne "${Color_Off}"
}

function separator- {
    separator "─"
}

function fclear {
    #echo -n -e "\e[0;37m\e[40m\ec"
    #echo -n -e "\ec\e[37m\e[40m\e[J"
    #echo -n -e "\ec${White}${On_Black}\e[J"
    echo -n -e "\ec${White}${On_Black}\e[J"
}

function cursor {
    local stato=$1
    case $stato in
	off)
	    echo -e -n "\033[?30;30;30c"
	    ;;
	on)
	    echo -e -n "\033[?0;0;0c"
	    ;;
    esac
}

function header {
    ## $1=label ; $2=colors ; $3=header pattern

    # echo -n -e "\e[1;34m $1 ${Color_Off}\n"
    local text="$1"
    local length_text=$(( ${#text}+2 ))
    local hpattern="$3"
    
    [ -z "$hpattern" ] && hpattern=" "
    echo -ne "$2"

    for column in `seq 1 $COLUMNS`
    do
	echo -ne "$hpattern" 
    done 

    if [ -n "$length_text" ] &&
	   [ -n "$COLUMNS" ]
    then
	if (( $length_text<=$COLUMNS ))
	then
	    echo -ne "\r$text${Color_Off}\n"

	else
	    echo -ne "\r${text:0:$COLUMNS}${Color_Off}${text:$COLUMNS}\n"
	fi
    fi
}

function header_z {
    local text_space
    #fclear
    zclock
    eval printf -v text_space "%.0s\ " {1..$(( $COLUMNS-45 ))}
    header " ZigzagProxy ($prog)${text_space}$zclock" "$On_Blue" " "
}

function header_box {
    header " $1 " "$Black${On_White}" "─" #"-" 
}

function header_line {
    header " $1 " "$White${On_Blue}" " "
}

function zclock {
    if [[ "${LANGUAGE}${LANG}" =~ (it|IT) ]]
    then
	week=( "dom" "lun" "mar" "mer" "gio" "ven" "sab" )

    else
	week=( "sun" "mon" "tue" "wed" "thu" "fri" "sat" )
    fi
    
    #zclock="\033[1;$((COLUMNS-22))f$(date +%R) │ ${week[$( date +%w )]} $(date +%d·%m·%Y)"
    zclock="$(date +%R) │ ${week[$( date +%w )]} $(date +%d·%m·%Y)"
}
#### end layout


function my_ip {
    # myip=$(wget -qO- \
    # 		checkip.dyndns.org |
    # 		  sed -e 's/.*Current IP Address: //' -e 's/<.*$//')
    print_c 4 "${msg[0]}" #"Indirizzo IP:"
    wget -qO- "$ip_server_url"
    echo
}

# function new_ip_router {
#     header_box "${msg[1]}" #"Riconnessione del modem (cambio indirizzo IP)"
    
#     if [ -s $credentials ]
#     then
# 	USER=$(awk '{print $1}' "$credentials")
# 	PASSWD=$(awk '{print $2}' "$credentials")

# 	my_ip
	
# 	print_c 1 "${msg[2]}" #"Cambio indirizzo IP..."
# 	wget --http-passwd=$PASSWD    \
# 	     --http-user=$USER        \
# 	     192.168.0.1/stanet.stm   \
# 	     -O- &>/dev/null

# 	wget --http-passwd=$PASSWD       \
# 	     --http-user=$USER           \
# 	     --post-data="disconnect=1"  \
# 	     192.168.0.1/cgi-bin/statusprocess.exe \
# 	     -O- &>/dev/null
# 	echo
	
# 	my_ip
#     else
# 	print_c 3 "${msg[3]}" #"Funzione disattivata: non esiste il file di configurazione $credentials"
#     fi

# }

function unset_proxy {
    unset http_proxy https_proxy
    export http_proxy https_proxy
}

function set_proxy {
    export http_proxy="$1"
    export https_proxy=$http_proxy
}

## servizi proxy:
function _proxyscrape {
    local yes_no
    unset http_proxy https_proxy

    if [ "$proxy_ssl" == true ]
    then
        yes_no=yes
        print_c 2 "HTTPS proxy"
    else
        yes_no=no
    fi

    if [ -n "${proxy_types[*]}" ] &&
           (( ${#proxy_types[*]} == 1 ))
    then
        proxy_type="${proxy_types[0]}"
        
    elif [ -z "${proxy_types[*]}" ] ||
             (( ${#proxy_types[*]} == 0 ))
    then
        proxy_type=Transparent
        
    else
        proxy_type=All
    fi
    
    wget "https://api.proxyscrape.com/v2/?request=getproxies&protocol=http&timeout=10000&country=all&ssl=${yes_no}&anonymity=${proxy_type}&simplified=true" \
         -qO- \
         -o /dev/null |
        tr -d '\r' |
        sed -r "s|(.+)|\1:$proxy_type|g" > "$path_tmp/proxy_list.txt" 
    
    [ -s "$path_tmp/proxy_list.txt" ] && return 0 || return 1
}

function _ip_adress {
    local proxy_regex
    ## ip-adress.com
    wget -q -t 1 -T 20                              \
	 --user-agent="$user_agent"                 \
	 ${proxy_list_sources[1]}                   \
	 -O "$path_tmp/proxy_page.html"             \
	 -o /dev/null

    for proxy_type in ${proxy_types[*]}
    do
	case "$proxy_type" in
	    Transparent)
		proxy_regex='<td>transparent'
		;;
	    Anonymous)
		proxy_regex='<td>anonymous'
		;;
	    Elite)
		proxy_regex='<td>highly-anonymous'
		;;
	esac
	
	grep "${proxy_regex}" "$path_tmp/proxy_page.html" -B1  |
	    grep href |
	    sed -r "s|.+>([^>]+)</a>([^<]+)<.+|\1\2:$proxy_type|g"  >> "$path_tmp/proxy_list.txt"
    done
}


function _proxy_list {
    #### attualmente non ancora integrata nel più recente sistema
    ## proxy-list.org
    wget -q -t 1 -T 20                              \
	 --user-agent="$user_agent"                 \
	 ${proxy_list_sources[2]}                   \
	 -O "$path_tmp/proxy_page.html"             \
	 -o /dev/null

    for proxy_type in ${proxy_types[*]}
    do
	html=$(grep -B 4 "${proxy_type}" "$path_tmp/proxy_page.html" |grep class)
    done
    ## da fare:
    ## sostituire $html con "$path_tmp"/proxy_list.txt: accodare in modo uniforme questi proxy con quelli dell'altro servizio
    

    ## get_proxy proxy:
    ##
    # n=$(( $(wc -l <<< "$html")/4 ))
    # proxy_type=$(sed -n $(( ${line}*4 ))p <<< "$html")
    # proxy_type="${proxy_type%%'</'*}"
    # proxy_type="${proxy_type##*>}"

    # proxy=$(sed -n $(( ${line}*4-3 ))p <<< "$html")
    # proxy="${proxy#*proxy\">}"
    # proxy="${proxy%<*}"
}

function get_proxy_list {
    print_c 4 "${msg[19]}: ${proxy_list_sources[0]}" #"Ricerca lista proxy"
    _proxyscrape

    if [ ! -s "$path_tmp/proxy_list.txt" ]
    then
	print_c 3 "${msg[4]}" #"Proxy non disponibili"
    fi
}

# function get_proxy_list {    
#     print_c 4 "$(gettext "Proxy list search") %s: %s" "$proxy_server" "${list_proxy_url[$proxy_server]}" 

#     $proxy_server
#     if [ ! -s "$path_tmp/proxy_list.txt" ]
#     then
# 	print_c 3 "$(gettext "Proxy not available, please try again later")" 
# 	break
#     fi
# }


function get_proxy {
    [ -s "$path_tmp/proxy_list.txt" ] || return 1
    
    declare -n ref_address="$1"
    declare -n ref_type="$2"
    local regex=$(tr ' ' '|' <<< "${proxy_types[*]}")
    
    local max=$(wc -l < "$path_tmp/proxy_list.txt")
    local proxy_line=$(grep -P "($regex)" "$path_tmp/proxy_list.txt" |head -n1)

    [[ "$proxy_line" =~ Anonymous ]] && ref_type="Anonymous"
    [[ "$proxy_line" =~ Transparent ]] && ref_type="Transparent"
    [[ "$proxy_line" =~ Elite ]] && ref_type="Elite"

    [ -z "${ref_type}" ] && ref_type=All
    
    ref_address="${proxy_line%:${ref_type}*}"
}

function del_proxy {
    local proxy_address="$1"
    local proxy_type="$2"

    if [ -s "$path_tmp/proxy_list.txt" ]
    then
	grep -v "${proxy_address}:${proxy_type}" "$path_tmp/proxy_list.txt" >"$path_tmp/proxy_list.temp"
	mv "$path_tmp/proxy_list.temp" "$path_tmp/proxy_list.txt"
    fi
}

function check_speed {
    ## $1 == url to test
    local maxspeed=0
    local minspeed=25
    local num_speed type_speed speed

    print_c 2 "${msg[5]}" #"Test velocità di download:"

    i=0
    while ((i<3))
    do
	i=${#speed[*]}
	#speed[$i]=$(wget -t 1 -T 60 -O /dev/null "http://indirizzo-ip.com/ip.php" 2>&1 | grep '\([0-9.]\+ [KM]B/s\)' )
	#speed[$i]=$(wget -t 1 -T $max_waiting -O /dev/null "$url_in" 2>&1 | grep '\([0-9.]\+ [KM]B/s\)' )

	wget -t 1 -T $max_waiting              \
	     --user-agent="$user_agent"        \
	     -O /dev/null                      \
	     "$1"                              \
	     -o "$path_tmp"/speed-test-proxy

	speed[$i]=$(grep '\([0-9.]\+ [KM]B/s\)' "$path_tmp"/speed-test-proxy)
	
	if [ -n "${speed[$i]}" ]
	then
	    speed[$i]="${speed[$i]#*'('}"
	    speed[$i]="${speed[$i]%%)*}"
	    
	    type_speed[$i]="${speed[$i]//[0-9. ]}"
	    num_speed[$i]="${speed[$i]//${type_speed[$i]}}"
	    num_speed[$i]="${num_speed[$i]//[ ]*}"
	    num_speed[$i]="${num_speed[$i]//[.,]*}"

	    if [ "${type_speed[$i]}" == 'B/s' ]
	    then
		num_speed[$i]="0"

	    elif [ "${type_speed[$i]}" == 'MB/s' ]
	    then
		num_speed[$i]=$(( ${num_speed[$i]}*1024 ))
	    fi
	else
	    speed[$i]="0 KB/s"
	    num_speed[$i]="0"
	    type_speed[$i]='KB/s'
	fi
	print_c 0 "${speed[i]}"

	if (( "${num_speed[0]}" == 0 ))
	then
	    break

	elif (( "${num_speed[i]}" >= 25 ))
	then
	    print_c 1 "${msg[6]} $http_proxy: ${num_speed[i]} KB/s" #"Velocità di download sufficiente usando il proxy"
	    echo "$http_proxy" > "$path_tmp"/proxy-active
	    return 0
	fi
    done 2>/dev/null
    
    for k in ${num_speed[*]}
    do
    	(( $maxspeed<$k )) && maxspeed=$k 
    done
    
    if (( $maxspeed<$minspeed ))
    then
    	print_c 3 "${msg[7]} ($minspeed KB/s)" #"La massima velocità di download raggiunta usando il proxy è inferiore a quella minima richiesta"
	rm -f "$path_tmp"/proxy-active
	return 1

    else
    	print_c 1 "${msg[8]} $http_proxy: $maxspeed KB/s" #"Massima velocità di download raggiunta usando il proxy"
    	return 0
    fi 
}

function display_proxy {
    if [ -n "$http_proxy" ]
    then
	print_c 1 "${msg[9]} $http_proxy\n" # "Proxy attivo:"

    else
	print_c 3 "${msg[10]}" #"Proxy non attivo\n"
    fi
}

function new_ip_proxy {
    header_box "${msg[11]} ${proxy_types[*]}" #"Attivazione proxy:"
    
    export LANG="$prog_lang"
    export LANGUAGE="$prog_lang"
    
    rm -f "$path_tmp/proxy.tmp" "$path_tmp/cookies.zdl" "$path_tmp/proxy_list.txt" 

    ##########################################
    ## tipi di proxy: Anonymous Transparent Elite
    ## da impostare nelle estensioni in cui si fa uso di check_ip:
    ## proxy_types=( ELENCO TIPI DI PROXY )
    ##
    ## predefinito:
    if [ -z "${proxy_types[*]}" ]
    then
	proxy_types=( "Transparent" )
    fi
    ##########################################
    
    while true
    do
	unset_proxy
	unset proxy_address proxy_type
	print_c 2 "${msg[12]} (${proxy_types[*]// /, }):" #"\nAggiorna proxy"
	
	if [ ! -s "$path_tmp/proxy_list.txt" ]
	then
	    get_proxy_list
	fi

	if [ -s "$path_tmp/proxy_list.txt" ]
	then
	    get_proxy proxy_address proxy_type
	fi
	
	if [ -n "$proxy_address" ]
	then
	    set_proxy "$proxy_address"
	    print_c 0 "Proxy: $http_proxy ($proxy_type)\n"
	    del_proxy "$proxy_address" "$proxy_type"

	    if check_speed "$ip_server_url"
	    then
		display_proxy
		break

	    elif [ ! -s "$path_tmp/proxy_list.txt" ]
	    then
		print_c 3 "${msg[13]}" #"Proxy attualmente non disponibile: proxy disattivato"
		break
	    fi
	    
	else
	    print_c 3 "${msg[13]}" #"Proxy attualmente non disponibile: proxy disattivato"
	    break
	fi
    done
    
    rm -f "$path_tmp/proxy_list.txt"

    export LANG="$user_lang"
    export LANGUAGE="$user_language"
}

function update_prog {
    local version
    local ok_update=false
    local pwd_old="$PWD"
    header_box "${msg[14]}" #"Aggiornamento di $PROG ..."

    if [ -s "$path_prog/version" ]
    then
	version=$(wget -qO- http://download-mirror.savannah.gnu.org/releases/zproxy/version)
	if [ "$version" != "$(cat "$path_prog/version")" ]
	then
	    ok_update=true
	fi
	
    else
	ok_update=true
    fi

    if $ok_update
    then
	cd /tmp
	wget -T $max_waiting "$url_update"

	print_c 4 "${msg[15]}" #"Installazione di $PROG in /usr/local/bin/ ..."
	archive="${url_update##*\/}"
	tar -xzf "$archive"
	rm -f "$archive"*

	cd "${archive%.tar.gz}"
	chmod +x $prog

	mv $prog /usr/local/bin/ &&
	    echo "$version" >"$path_prog/version" &&
	    print_c 1 "${msg[16]}" || #"Aggiornamento completato."
		(
		    sudo mv $prog /usr/local/bin/ &&
			echo "$version" >"$path_prog/version" &&
			print_c 1 "${msg[16]}"
		) || #"Aggiornamento completato."
		(
		    echo -n "(Root)" &&
			su -c "mv $prog /usr/local/bin/" &&
			echo "$version" >"$path_prog/version" &&
			print_c 1 "${msg[16]}"
		) || #"Aggiornamento completato." 
		print_c 3 "${msg[17]}" #"Aggiornamento automatico non riuscito"
	echo
	cd "$pwd_old"

    else
	print_c 1 "${msg[20]}" ## già aggiornato all'ultima versione
    fi
}

function get_firefox_profile {
    firefox_profile_path=$(grep -A1 \
				'IsRelative=1' \
				"$HOME/.mozilla/firefox/profiles.ini" |
				  tail -n1)
    firefox_profile_path="${HOME}/.mozilla/firefox/${firefox_profile_path#Path=}"
    
    if [ -s "$firefox_profile_path/prefs.js" ]
    then
	mkdir -p "$firefox_profile_path_bak"
	# cp -rf "${path}"/* "$firefox_profile_path"
	# sed -i -r "s|${path}|$firefox_profile_path|g" "$firefox_profile_path"/extensions.ini

	cp -rf "$firefox_profile_path"/prefs.js "$firefox_profile_path_bak"

	# firefox_profile_path="$path"
	# cp "${path}/prefs.js" "${path}/prefs.js.bak" 
    fi	
}

function add_firefox_proxy {
    echo -e "
user_pref(\"network.proxy.http\", \"${http_proxy%:*}\");
user_pref(\"network.proxy.http_port\", ${http_proxy#*:});
user_pref(\"network.proxy.type\", 1);
" >>"$firefox_profile_path"/prefs.js
}

function del_firefox_proxy {
    mv "$firefox_profile_path_bak/prefs.js" "$firefox_profile_path/prefs.js"
    rm -fr "$firefox_profile_path_bak"
    
    
#    mv "$firefox_profile_path/prefs.js.bak" "$firefox_profile_path/prefs.js" 
}

function usage {
    if [[ "${LANGUAGE}${LANG}" =~ (it|IT) ]]
    then
	print_c 4 "Uso (l'ordine degli argomenti non è importante):"
	echo -e "\t[source|.] $prog [opzioni] [comandi|programmi]
"
	print_c 4 "[source|.]:"
	echo -e "È possibile attivare/disattivare un proxy per tutti
i programmi/comandi avviati dallo stesso terminale: 
'source' (abbreviato con un punto, deve essere sempre 
inserito PRIMA del comando) 'globalizza' le variabili 
'http_proxy' e 'https_proxy', rendendole attive per tutte 
le applicazioni avviate dal terminale dopo ZigzagProxy.
"
	
	print_c 4 "Opzioni:"
	echo -e "-h,	--help		      Manuale di ZigzagProxy

        --ip                  Indirizzo IP attuale

-u      --update              Aggiorna ZigzagProxy
	
-d      --disable             Disabilita il proxy

-s      --ssl                 Proxy HTTPS (ssl)
	
-t      --transparent         Seleziona il tipo di proxy 
-a      --anonymous           automatico da attivare:
-e      --elite               Transparent, Anonymous, Elite

-p PROXY, -pPROXY 	      [-p|--proxy=] permette di attivare 
        --proxy=PROXY         un PROXY scelto dall'utente

"
	print_c 4 "\nComandi o programmi:"
	echo -e "Il programma o i comandi da avviare con proxy attivo. 
In presenza di argomenti o, comunque, di spazi, 
è necessario racchiudere il comando fra le 
virgolette o gli apici singoli.
"
	print_c 4 "\nNote:"
	echo -e "ZigzagProxy può attivare un proxy anche 
per Chrome/Chromium and Firefox. 
"

	print_c 4 "Copyright (C):"
	echo -e "Gianluca Zoni <zoninoz@inventati.org>, 2012\n"

	print_c 4 "Licenza:"
	echo -e "GNU/GPL v.3 o successive: http://www.gnu.org/licenses/\n"

    else
	print_c 4 "Usage (the order of the arguments is not important):"
	echo -e "\t[source |.] zproxy [options] [commands | programs]\n"

	print_c 4 "[Source |.]:"
	echo -e "You can activate/deactivate a proxy for all
programs/commands started from the same terminal:
'source' (abbreviated with a dot, must always be
inserted BEFORE the command) 'globalizes' the variables
'http_proxy' and 'https_proxy', making it active 
for all commands/programs started from the terminal 
after ZigzagProxy.\n"
	
	print_c 4 "Options:"
	echo -e "
-h,     --help                ZigzagProxy Manual

        --ip                  Current IP address

-u      --update              Update ZigzagProxy

-d      --disable             Disable the proxy

-s      --ssl                 HTTPS proxy (ssl)

-t      --transparent         Select the type of automatic
-a      --anonymous           proxy to activate:
-e      --elite               Transparent, Anonymous, Elite

-p PROXY, -pPROXY             [-p|--proxy=] allows to activate
	--proxy=PROXY         a PROXY chosen by the user

"
	print_c 4 "Commands or programs:"
	echo -e "The program or commands to be started with active proxy.
In the presence of arguments or, in any case, of spaces,
it is necessary to enclose the command between 
quotes or single quotes.\n"


	print_c 4 "Note:"
	echo -e "ZigzagProxy can also activate a proxy
for Chrome/Chromium and Firefox.\n"

	print_c 4 "Copyright (C):"
	echo -e "Gianluca Zoni <zoninoz@inventati.org>, 2012\n"

	print_c 4 "License:"
	echo -e "GNU/GPL v.3 or later: http://www.gnu.org/licenses/\n"
    fi
}


init_colors
header_z

proxy_types=()

if (( $#>0 ))
then
    args=( "$@" )

    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]{2}$ ]]
	    then
		for ((j=1; j<${#args[i]}; j++))
		do
	            args[++max_args]="-${args[i]:$j:1}"
		done
		unset args[i]
	    fi
	done
    fi

    i=0
    while (( i<=$max_args ))
    do
	case "${args[i]}" in
	    -u | --update) 
		update=true
		;;
	    -h | --help)
		help=true
		;;
	    -d | --disable)
		disable_proxy=true
		;;
	    -s | --ssl)
		proxy_ssl=true
		;;
	    -t | --transparent)
		transparent=true
		[[ "${proxy_types[*]}" =~ Transparent ]] ||
		    proxy_types+=( Transparent )
		;;
	    -a | --anonymous)
		anonymous=true
		[[ "${proxy_types[*]}" =~ Anonymous ]] ||
		    proxy_types+=( Anonymous )
		;;
	    -e | --elite)
		elite=true
		[[ "${proxy_types[*]}" =~ Elite ]] ||
		    proxy_types+=( Elite )
		;;
	    # -r | --reconnect)
	    #     reconnect=true
	    #     ;;
	    --ip)
		ip=true
		;;
	    -p)
		if [[ "${args[i+1]}" =~ ^([0-9.:]+)$ ]]
		then
		    set_proxy "${args[i+1]}"
		    display_proxy
		    unset args[i+1]
		fi
		;;
	    '')
		;;
	    *)
		if command -v "${args[i]%% *}" &>/dev/null
		then
		    cmds+=( "${args[i]}" )
		    unset args[i]
		    
		elif [[ "${args[i]}" =~ ^\-(p|\-proxy=)([0-9.:]+)$ ]]
		then
		    set_proxy "${BASH_REMATCH[2]}"
		    display_proxy

		else
		    usage
		    exit 1
		fi
		;;
	esac
	(( i++ ))
	
    done
    
    if [ -z "${proxy_types[*]}" ]
    then
	proxy_types=( "Transparent" )
    fi
    
    "$help" && usage	
    
    $update && update_prog
    # $reconnect && new_ip_router
    $disable_proxy && unset_proxy && print_c 1 "${msg[18]}" #"Proxy disattivato\n"

    if $transparent ||
	    $anonymous ||
	    $elite
    then
	new_ip_proxy
    fi

    $ip && my_ip

    for cmd in "${cmds[@]}"
    do
	if command -v "${cmd%% *}" &>/dev/null
	then
	    if [[ "${cmd%% *}" =~ (firefox|iceweasel|conkeror) ]]
	    then
		if [ -n "${http_proxy}${https_proxy}" ]
		then
		    get_firefox_profile
		    add_firefox_proxy
		fi
		
		urls=( $cmd )
		unset urls[0]

		${cmd%% *} ${urls[@]} #--profile "$firefox_profile_path"

		if [ -n "${http_proxy}${https_proxy}" ]
		then
		    del_firefox_proxy
		fi
		
	    else
		$cmd
	    fi
	    
	else
	    print_c 3 "${cmd%% *} ${msg[21]}"
	fi
    done
    
else
    usage
fi

