#!/bin/bash

################################################################################
#      This file is part of OpenELEC - http://www.openelec.tv
#      Copyright (C) 2009-2016 Stephan Raue (stephan@openelec.tv)
#
#  OpenELEC 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 2 of the License, or
#  (at your option) any later version.
#
#  OpenELEC 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 OpenELEC.  If not, see <http://www.gnu.org/licenses/>.
################################################################################

. config/options $1

if [ -z "$1" ]; then
  for i in `find packages/ -type f -name package.mk`; do
    GET_PKG=`grep ^PKG_NAME= $i | sed -e "s,\",,g" -e "s,PKG_NAME=,,"`
    $SCRIPTS/get $GET_PKG
  done
fi

if [ -n "$PKG_URL" -a -n "$PKG_SOURCE_NAME" ]; then
  mkdir -p $SOURCES/$1

  # Avoid concurrent downloads of the same package
  _isblocked=N
  exec 99<$SOURCES/$1
  while ! flock --nonblock --exclusive 99; do
    [ ${_isblocked} == N ] && { echo "Project ${PROJECT} waiting to avoid concurrent download of ${1}..."; _isblocked=Y; }
    sleep 1
  done

  PACKAGE="$SOURCES/$1/$PKG_SOURCE_NAME"
  PACKAGE_MIRROR="$DISTRO_MIRROR/$PKG_NAME/$PKG_SOURCE_NAME"
  [ "$VERBOSE" != "yes" ] && WGET_OPT=-q
  WGET_CMD="wget --timeout=30 --tries=3 --passive-ftp --no-check-certificate -c $WGET_OPT -O $SOURCES/$1/$PKG_SOURCE_NAME"

  NBWGET="1"

  STAMP="$PACKAGE.url"
  MD5SUM="$PACKAGE.md5"

  DL="yes"
  if [ -f "$STAMP" ]; then
    [ "`cat $STAMP`" == "$PKG_URL" ] && DL="no"
  fi

  if [ "$DL" == "yes" ]; then
    rm -f $STAMP

    printf "%${BUILD_INDENT}c ${boldcyan}GET${endcolor}      $1\n" ' '>&$SILENT_OUT
    export BUILD_INDENT=$((${BUILD_INDENT:-1}+$BUILD_INDENT_SIZE))

    until [ -f "$STAMP" ] || $WGET_CMD $PKG_URL || $WGET_CMD $PACKAGE_MIRROR; do
      NBWGET=$(($NBWGET+1))
      if [ "$NBWGET" -gt "10" ]; then
        echo -e "\nCant't get $1 sources : $PKG_URL\n Try later !!"
        exit 1
      fi
    done

    echo $PKG_URL > $STAMP
    md5sum -t $PACKAGE > $MD5SUM

    rm -f $BUILD_BASE*/$STAMPS_NOARCH/$1/unpack
    rm -f $BUILD_BASE*/$STAMPS_NOARCH/$1/build
  fi
fi

exit 0
