#!/bin/sh
#
#  srcget - source repository downloader
#  Copyright (C) 2012 Jaromir Capik <tavvva@email.cz>
#
#  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/>.
#

URL='http://delicate-linux.net'

function usage() {
  echo
  echo "Usage: srcget [delicate-version [package-name [package-version]]]"
  echo
}

created=0

if [ "$1" == "" ]; then  # DeLi(cate) version not specified
  echo "DeLi(cate) version not specified!"
  usage
else
  if [ "$2" == "" ]; then  # package name not specified ... list all packages
    echo "Package name not specified!"
    usage
    echo "Available sources:"
    curl $URL/$1/src/ 2>/dev/null | sed 's|\[DIR\]|\n\[DIR\]|g' | grep '\[DIR\]' | grep -v 'Parent Directory' | cut -f2- -d'=' | cut -f2 -d'"' | cut -f1 -d'/'
  else
    if [ "$3" == "" ]; then  # package version not specified ... list all versions
      echo "Package version not specified!"
      usage
      echo "Available versions:"
      curl $URL/$1/src/$2/ 2>/dev/null | sed 's|\[DIR\]|\n\[DIR\]|g' | grep '\[DIR\]' | grep -v 'Parent Directory' | cut -f2- -d'=' | cut -f2 -d'"' | cut -f1 -d'/'
    else
      curl $URL/$1/src/$2/$3/ 2>/dev/null | sed 's|href|\nhref|g' | grep -A 9999 '\[DIR\]' | grep -v 'Parent Directory' | grep -v 'img src' | grep "href" | cut -f2- -d'=' | cut -f2 -d'"' | cut -f1 -d'/' | while read filename; do
        [ $created = 0 ] && created=1 && mkdir -p $1/$2/$3 && cd $1/$2/$3
        wget $URL/$1/src/$2/$3/$filename
      done
      [ $created = 0 ] && echo "Requested sources not found!"
    fi
  fi
fi
