#!bash
# vim:ff=unix:enc=utf8:ts=3:sw=3:et

# src2pkg-ng - package creation toolkit
# Copyright (C) 2005-2009 Gilbert Ashley
# Copyright (C) 2009 Timothy Goya

# src2pkg-ng is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License, version 2 as 
# published by the Free Software Foundation

# src2pkg-ng 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 src2pkg-ng.  If not, see <http://www.gnu.org/licenses/>.

download_ftp() {
   declare URL="$1"
   if which wget > /dev/null 2>&1 ; then
      wget -q -O - "$URL"
   elif which curl > /dev/null 2>&1 ; then
      curl -s -S "$URL"
   elif which lynx > /dev/null 2>&1 ; then
      lynx -source "$URL"
   # FIXME: Create nc and telnet downloaders
   # FIXME: Figure out another way to determine net redirects support
   elif cat < "/dev/tcp/time.nist.gov/13" > /dev/null 2>&1 ; then
      declare HOST="${URL#"ftp://"}"
      declare LOC="${HOST#*/}"
      HOST="${HOST%%/*}"
      declare PORT="${HOST##*:}"
      if [[ "$PORT" == "$HOST" ]] ; then
         PORT="21"
      fi
      HOST="${HOST%:*}"
      declare LINE=""
      declare STATUS=""
      declare REASON=""
      read_reply() {
         STATUS="1"
         while [[ "${STATUS:0:1}" == "1" ]] ; do
            read -r -u $FD LINE 
            LINE=${LINE%$'\r'}
            STATUS=${LINE%% *}
            REASON=${LINE#* }
         done
         if [[ "${STATUS:0:1}" == "2" || "${STATUS:0:1}" == "3" ]] ; then
            return 0
         fi
         eval "exec $FD>&-"
         return 1
      }
      declare FD=3
      while [[ -L "/dev/fd/$FD" ]] ; do
         (( ++FD ))
      done
      eval "exec $FD<>/dev/tcp/$HOST/$PORT"
      read_reply
      echo "USER anonymous" >&$FD
      read_reply
      echo "PASS anonymous@" >&$FD
      read_reply
      echo "TYPE I" >&$FD
      read_reply
      echo "PASV" >&$FD
      read_reply
      unset -f read_reply
      declare DATA_HOST="${REASON#*(}"
      DATA_HOST="${DATA_HOST%)*}"
      declare DATA_PORT_LOW="${DATA_HOST##*,}"
      DATA_HOST="${DATA_HOST%,*}"
      declare DATA_PORT_HIGH="${DATA_HOST##*,}"
      declare DATA_PORT=$(( DATA_PORT_HIGH * 256 + DATA_PORT_LOW ))
      DATA_HOST="${DATA_HOST%,*}"
      DATA_HOST="${DATA_HOST//,/.}"
      declare DATA_FD=3
      while [[ -L "/dev/fd/$DATA_FD" ]] ; do
         (( ++DATA_FD ))
      done
      echo "RETR $LOC" >&$FD
      eval "exec $DATA_FD</dev/tcp/$DATA_HOST/$DATA_PORT"
      cat <&$DATA_FD
      eval "exec $DATA_FD>&-"
      echo "QUIT" >&$FD
      eval "exec $FD>&-"
      return 0
   fi
}
