#!/bin/sh
#(c) Copyright Barry Kauler 2010. License GPL v3 /usr/share/doc/legal.
#BK a simple frontend for wget.
#URL passed in, only downloads to current directory.
#only put up user-response dlg windows if failure.
#101116 first version.
#101117 url sanity check. more download size check.
#101118 for ftp connection have to get size differently.
#101126 not sure, it seems that wget now defaults to ipv6, fails for some users, use '-4' to force ipv4.
#101206 fix find filesize ftp://ftp.lug.udel.edu/pub/puppylinux ...
# 19dec10 shinobar: i18n with gettext

#exit number: 0 ok, 1 unable to download, 2 download fail, 3 invalid url.

#export LANG=C #keep Xdialog happy.
URLSPEC="$@"
FILENAME="`basename "$@"`"
. /etc/rc.d/PUPSTATE
RXVT="rxvt"
which urxvt &>/dev/null && RXVT="urxvt"
XDIALOG="Xdialog"
which gxdialog &>/dev/null && XDIALOG="gxdialog"
export TEXTDOMAIN=dotpup
export TEXTDOMAINDIR=/usr/share/locale
export OUTPUT_CHARSET=UTF-8

if [ "$URLSPEC" = "" ]; then
 echo "Usage: download_file URL" >&2
 $XDIALOG --wmclass "gtkdialog2" --title "$(gettext 'Puppy File Downloader')" --screen-center --cr-wrap --icon "/usr/local/lib/X11/pixmaps/error.xpm" --msgbox "$(gettext 'No URL specified')" 0 0
 exit 1
fi

#test url... -t 2 means try 2 times, -T 20 means timeout in 20 seconds
while [ 1 ];do
 echo -n "" > /tmp/download_file_spider.log1
 #gtklogfileviewer "/tmp/download_file_spider.log" "Close" 0 0 600 200 "Testing remote file exists:" &
 $RXVT -geometry 130x10+0+0 -bg orange -fg black -title "$(gettext 'Testing file exists'): ${URLSPEC}" -e tail -f /tmp/download_file_spider.log1 &
 PID1=$!
 LANG=C wget -4 -t 2 -T 20 --waitretry=20 --spider -S "${URLSPEC}" > /tmp/download_file_spider.log1 2>&1
 if [ $? -ne 0 ];then
  $XDIALOG --wmclass "gtkdialog2" --title "$(gettext 'Puppy File Downloader')" --screen-center --cr-wrap --ok-label "$(gettext 'TEST AGAIN')" --cancel-label "$(gettext 'GIVE UP')" --icon "/usr/local/lib/X11/pixmaps/error.xpm" --yesno "$(gettext 'Tested if remote file exists, but failed, see log top-left of screen.
Do you want to test again, or give up?')" 0 0
  REPLY1=$?
  kill $PID1
  [ $REPLY1 -eq 0 ] && continue
  exit 1
 fi
 kill $PID1
 break
done

#find out size of online file...
SIZEB_ONLINE=`grep '^Length: ' /tmp/download_file_spider.log1 | tr -s ' ' | cut -f 2 -d ' ' | sed -e 's%[^0-9]%%g'`
#101118 for ftp connection have to get size differently...
[ "$SIZEB_ONLINE" = "" ] && SIZEB_ONLINE=`grep "${FILENAME}" /tmp/download_file_spider.log1 | tr '\t' ' ' | tr -s ' ' | grep ' ftp ' | cut -f 5 -d ' ' | sed -e 's%[^0-9]%%g'`
#101206 ftp://ftp.lug.udel.edu/pub/puppylinux/pet_packages-3/gpm-1.20.1-1.pet ...
[ "$SIZEB_ONLINE" = "" ] && SIZEB_ONLINE=`grep "${FILENAME}" /tmp/download_file_spider.log1 | tr '\t' ' ' | tr -s ' ' | grep ' root ' | cut -f 5 -d ' ' | sed -e 's%[^0-9]%%g'`
[ "$SIZEB_ONLINE" = "" ] && SIZEB_ONLINE=`grep "${FILENAME}" /tmp/download_file_spider.log1 | tr '\t' ' ' | tr -s ' ' | grep ' 2[0-9][0-9][0-9] ' | cut -f 5 -d ' ' | sed -e 's%[^0-9]%%g'`
#101117 sanity check...
URL_BROKEN='0'
if [ "$SIZEB_ONLINE" = "" ];then
 MSG_NO1="$(gettext 'Oh dear, unable to obtain size of remote file'):
${URLSPEC}
$(gettext 'although it does seem to exist.')"
 URL_BROKEN='1'
else
 case $SIZEB_ONLINE in
  unspecified)
   MSG_NO1="$(gettext 'Oh dear, this URL seems to be wrong'):
${URLSPEC}
$(gettext 'It is supposed to be of the format http://foo.org/abiword-1.pet,
or ftp://foo.org/abiword-1.pet (with name of the file to download
on the end), but your URL seems wrong.')"
   URL_BROKEN='1'
  ;;
  *[a-zA-Z]*)
   MSG_NO1="$(gettetx 'Oh dear, something seems to be wrong with the URL'):
${URLSPEC}
$(gettext 'A probe of the remote file could not retrieve correct information
on it. ')"
   URL_BROKEN='1'
  ;;
 esac
fi
if [ "$URL_BROKEN" != "0" ];then
 $XDIALOG --wmclass "gtkdialog2" --title "$(gettext 'Puppy File Downloader')" --screen-center --cr-wrap --icon "/usr/local/lib/X11/pixmaps/error.xpm" --msgbox "${MSG_NO1}

$(gettext 'Click button to abort download')..." 0 0
 exit 3
fi

#101117 check enough free space...
#FREEK=`df -k | grep ' /$' | tr -s ' ' | cut -f 4 -d ' '`
#no, need to know free space in whatever is current dir...
PWD="`pwd`"
FREEblocks=`stat -f --format=%a ${PWD}`
BLOCKsize=`stat -f --format=%S ${PWD}`
FREEbytes=`expr $FREEblocks \* $BLOCKsize`
FREEK=`expr $FREEbytes \/ 1024`

SIZEK_ONLINE=`expr $SIZEB_ONLINE \/ 1024`
case $PUPMODE in
 3|7|13|77) #tmpfs on top
  #when install pkg, it writes direct to save-layer.
  SIZEK_REQUEST=`expr $SIZEK_ONLINE + 6000` #6MB slack.
 ;;
 *)
  SIZEK_REQUEST=`expr $SIZEK_ONLINE \* 3` #3MB slack, no, need install space too.
 ;;
esac
if [ $SIZEK_REQUEST -gt $FREEK ];then
 case $PUPMODE in
  5)
   MSGs=$(gettext 'You need to shutdown and create a save-file, then you will have more space.
See menu Shutdown -> Reboot')
  ;;
  2|6)
   MSGs=$(gettext 'The partition is full, you will have to delete something.')
  ;;
  3|7|77) #tmpfs on top, full partition underneath
   MSGs=$(gettext 'Do not have enough space in the RAM. Maybe you need a swap file
or swap partition (or it needs to be bigger)')
  ;;
  *)
   MSGs=$(gettext 'You need to increase the size of the save-file.
See menu Utility -> Resize personal storage file')
  ;;
 esac
MSGsize=$(gettext 'The online file is %sKB, but your free space is %sKB.')
MSGsize=T$(printf "$MSGsize" ${SIZEK_ONLINE} ${FREEK})

$XDIALOG --wmclass "gtkdialog2" --title "$(gettext 'Puppy File Downloader')" --screen-center --cr-wrap --icon "/usr/local/lib/X11/pixmaps/error.xpm" --msgbox "
$(gettext 'Sorry, but there is not enough free space to download to.
Attempted download directory'): ${PWD}
$MSGsize

${MSGs}

$(gettext 'Click button to abort download')..." 0 0
 exit 1
fi

INSERT1="already "
MSG=$(gettext "File '%s' is already partly downloaded (although there is
no guarantee it is uncorrupted), do you want to continue downloading it,
or erase it and download entire file again?")
MSG=$(printf "$MSG" ${FILENAME})
while [ 1 ];do

 CONTPARAM=''
 if [ -f $FILENAME ];then
  SIZEB_LOCAL=`stat --format=%s "${FILENAME}"`
  if [ $SIZEB_LOCAL -lt $SIZEB_ONLINE ];then
   MSG=$(gettext "File '%s' is already partly downloaded (although there is
no guarantee it is uncorrupted), do you want to continue downloading it,
or erase it and download entire file again?")
   MSG=$(printf "$MSG" ${FILENAME})
   $XDIALOG --wmclass "gtkdialog2" --title "$(gettext 'Puppy File Downloader')" --screen-center --cr-wrap --ok-label "$(gettext 'CONTINUE')" --cancel-label "$(gettext 'START AGAIN')"  --icon "/usr/local/lib/X11/pixmaps/question.xpm" --yesno "$MSG" 0 0
   if [ $? -eq 0 ];then
    CONTPARAM='-c'
   else
    rm -f "$FILENAME"
   fi
  else
   if [ $SIZEB_LOCAL -gt $SIZEB_ONLINE ];then #101117
     MSG=$(gettext "File '%s' is already downloaded but is larger
than the online file. Hmmm... this probably means that the online
file is a more recent version, so it is recommended that you erase
the local file and download it again...
Do you want to erase it and download entire file again?")
    MSG=$(printf "$MSG" ${FILENAME})
    $XDIALOG --wmclass "gtkdialog2" --title "$(gettext 'Puppy File Downloader')" --screen-center --cr-wrap --ok-label "$(gettext 'DOWNLOAD AGAIN')" --cancel-label "$(gettext 'NO')"  --icon "/usr/local/lib/X11/pixmaps/error.xpm" --yesno "$MSG" 0 0
    if [ $? -eq 0 ];then
     rm -f "$FILENAME"
    else
     exit 0
    fi
   else
     MSG=$(gettext "File '%s' is ${INSERT1}fully downloaded (although there is
no guarantee it is uncorrupted), do you want to erase it and download
entire file again?")
    MSG=$(printf "$MSG" ${FILENAME})
    $XDIALOG --wmclass "gtkdialog2" --title "$(gettext 'Puppy File Downloader')" --screen-center --cr-wrap --ok-label "$(gettext 'DOWNLOAD AGAIN')" --cancel-label "$(gettext 'NO')"  --icon "/usr/local/lib/X11/pixmaps/question.xpm" --yesno "$MSG" 0 0
    if [ $? -eq 0 ];then
     rm -f "$FILENAME"
    else
     exit 0
    fi
   fi
  fi
 fi

 echo -n "" > /tmp/download_file_spider.log2
 $RXVT -geometry 130x10+0+0 -bg orange -fg black -title "$(gettext 'Downloading file'): ${URLSPEC}" -e tail -f /tmp/download_file_spider.log2 &
 PID1=$!
 #-t 5 means retry 5 times, -w 5 means wait 5 seconds between retries...
 wget -4 ${CONTPARAM} -t 5 -w 5 "${URLSPEC}" > /tmp/download_file_spider.log2 2>&1
 if [ $? -ne 0 ];then
  $XDIALOG --wmclass "gtkdialog2" --title "$(gettext 'Puppy File Downloader')" --screen-center --cr-wrap --ok-label "$(gettext 'TRY AGAIN')" --cancel-label "$(gettext 'GIVE UP')" --icon "/usr/local/lib/X11/pixmaps/error.xpm" --yesno "$(gettext 'Download failed, see log top-left of screen.
Do you want to try again, or give up?')" 0 0
  REPLY1=$?
  kill $PID1
  [ $REPLY1 -eq 0 ] && continue
  rm -f "$FILENAME"
  exit 2
 fi
 kill $PID1
 
 paranoid, check size of downloaded file...
 SIZEB_LOCAL=`stat --format=%s "${FILENAME}"`
 if [ $SIZEB_LOCAL -ne $SIZEB_ONLINE ];then
  INSERT1=''
  continue
 fi
 
 break
done

exit 0
###END###
