#!/bin/sh
# $Id: wget,v 1.14 2019/08/28 22:15:03 friedman Exp $

# This is a wrapper because a static .wgetrc file might try to use options
# which older versions do not support.

wget=`run-next -p "$0" || echo :`

# Many websites block wget based on user agent.  So fabricate a different one.
user_agent="Mozilla/5.0 (X11; Fedora; Linux x86_64; rv:68.0) Gecko/20100101 Firefox/68.0"

XDG_CONFIG_HOME=${XDG_CONFIG_HOME-$HOME/.config}
XDG_DATA_HOME=${XDG_DATA_HOME-$HOME/.local/share}

cookies=$XDG_DATA_HOME/wget/cookies.txt
   hsts=$XDG_DATA_HOME/wget/hsts.txt

# Get major/minor/patch version numbers for wget
eval `$wget --version \
        | sed -ne '1s/^.*get \([0-9]*\)\.\([0-9]*\)\.\([0-9]*\).*.*/vmajor=\1 vminor=\2 vpatch=\3/p'`

case $vmajor:$vminor in
    : | *: | :* ) exit 1 ;;
esac

atleast()
{
    [ $vmajor -gt $1 ] \
        || [ $vmajor -eq $1 ] && [ $vminor -gt $2 ] \
        || [ $vmajor -eq $1 ] && [ $vminor -eq $2 ] && [ $vpatch -ge ${3-0} ]
}

opts="--wait=0
      --tries=0
      --cache=off
      --passive-ftp
     "
     #--follow-ftp

case " $* " in
    *" -q "* | *" --quiet "* ) : ;;
    * ) opts="$opts
              --verbose
              --server-response
             " ;;
esac

# wget 1.11.1 doesn't allow -N (--timestamping) with -O
case " $* " in
    *" -O "* ) : ;;
    * ) opts="$opts
              --timestamping
             " ;;
esac

if atleast 1 6; then
    opts="$opts
          --waitretry=60
         "
fi

if atleast 1 7 && [ -f "$cookies" ]; then
    opts="$opts
          --cookies=on
          --load-cookies=$cookies
         "
    if [ -w "$cookies" ] && [ ! -h "$cookies" ]; then
        opts="$opts
              --save-cookies=$cookies
              --keep-session-cookies
             "
    fi
fi

if atleast 1 8 && [ -t 1 ]; then
    # Use in-place progress bar if stdout is a tty
    opts="$opts --progress=bar:force"
fi

# Add timeout and retry options to wget 1.9 and later
if atleast 1 9; then
    opts="$opts
          --dns-timeout=30
          --connect-timeout=30
          --read-timeout=300

          --retry-connrefused
         "
         #--dns-cache=off
fi

#if atleast 1 20 3 ; then
#    opts="$opts --auth-no-challenge"
#fi

#if atleast 1 13; then
#    # use the name specified by the redirection url's last component
#    opts="$opts --trust-server-names"
#fi

if atleast 1 17; then
    opts="$opts
          --hsts
          --hsts-file=$hsts
         "
fi

conf=$XDG_CONFIG_HOME/wget/wgetrc
case ${WGETRC+isset} in
    isset ) : ;;
    * ) if [ -f "$conf" ] && ! [ -f "$HOME/.wgetrc" ]; then
            opts="$opts --config=$conf"
        fi ;;
esac

exec $wget \
     --user-agent="$user_agent" \
     --execute 'robots = off' \
     $opts "$@"

# wget ends here
