#!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_http() {
   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
      connect() {
         declare HOST="${URL#"http://"}"
         declare LOC="/${HOST#*/}"
         HOST="${HOST%%/*}"
         declare PORT="${HOST##*:}"
         if [[ "$PORT" == "$HOST" ]] ; then
            PORT="80"
         fi
         HOST="${HOST%:*}"
         eval "exec $FD<>/dev/tcp/$HOST/$PORT"
         echo "GET $LOC HTTP/1.1" >&$FD
         echo "Host: $HOST" >&$FD
         echo "" >&$FD
         read -r -u $FD LINE 
         LINE="${LINE%$'\r'}"
         HTTP_PROTOCOL="${LINE%% *}"
         LINE="${LINE#* }"
         STATUS="${LINE%% *}"
         REASON="${LINE#* }"
      }
      declare FD=3
      while [[ -L "/dev/fd/$FD" ]] ; do
         (( ++FD ))
      done
      declare LINE
      declare HTTP_PROTOCOL
      declare STATUS
      declare REASON
      connect
      while [[ "${STATUS:0:1}" = "3" ]] ; do
         read -r -u $FD LINE
         while [[ "${LINE:0:8}" != "Location" ]] ; do
            read -r -u $FD LINE
         done
         LINE="${LINE%$'\r'}"
         URL="${LINE#"Location: "}"
         eval "exec $FD>&-"
         connect
      done
      unset -f connect
      if [[ "$STATUS" == "200" ]] ; then
         read -r -u $FD LINE 
         while [[ "$LINE" != $'\r' ]] ; do
            read -r -u $FD LINE
         done
         cat <&$FD
         eval "exec $FD>&-"
         return 0
      else
         eval "exec $FD>&-"
         echo "$REASON"
         return 1
      fi
   fi
}
