#!/bin/bash
#
# Helper script for install-assist package.
# arguments 1:package name, 2 and on: download url
#
# NOTE: To avoid scriptlet failure during rpm transaction,
#       This script should always return 0 even if there is an error.

TEXTDOMAIN=self-build-setup
TEXTDOMAINDIR=/usr/share/locale

_NAME=$1
_QUEDIR=/var/cache/self-build
_ARCHIVEDIR=/var/cache/apt/archives

. /etc/self-build.conf

# create temporary directory to save downloaded file(s)
if ! _TOPDIR=`mktemp -d $TEMP_DIR/$_NAME.XXXXXX`; then
    echo -n "     "
    echo $"*ERROR: can't crete temporary directory."
    exit 0
fi

# get target package
echo -n "     "
echo $"Downloading rpm files..."
shift 1
for u in $@; do
    # if you already downloaded rpm files, 
    # then copy these from archived directory
    _TGT=$_TOPDIR/$(basename $u)
    _ARCHIVEDTGT=$_ARCHIVEDIR/$(basename $u)
    if [ "$CACHE_DOWNLOADED_FILES" = "yes" ]; then
	[ -s $_ARCHIVEDTGT ] && cp -af $_ARCHIVEDTGT $_TGT
    fi
    [ -s $_TGT ] && continue

    if [ ! $DL_SHOW_PROGRESS = "yes" ]; then
        # run quiet, no GUI 
        wget ${WGET_OPTS} -q -O $_TOPDIR/$(basename $u) $u
        RESULT=$?
    elif [ -z `pgrep -n synaptic` ]; then
        # run verbose, no GUI (because no synaptic running)
        wget ${WGET_OPTS} -O $_TOPDIR/$(basename $u) $u
        RESULT=$?
    else
    	# run verbose with GUI (zenity)
    	DLSTAT=0
        DLSTAT=(`wget ${WGET_OPTS} -O $_TOPDIR/$(basename $u) $u 2>&1 | \
             sed -u 's/.* \+\([0-9]\+%\).*$/\1/' 2>/dev/null | \
             zenity --auto-close --progress --auto-kill \
                     --title $"Download files" \
                     --text $"Downloading $(basename $u)..."; echo ${PIPESTATUS[0]}`)
        RESULT=$?
        # need to use string cpmparison for DLSTAT because PIPESTATUS[0] returns
        # null value when wget is killed with zenity auto-kill function.
        if [ "$DLSTAT" == "0" ] && [ $RESULT -eq 0 ]; then
            RESULT=0
        else
            RESULT=1
        fi
    fi
    [ $RESULT -ne 0 -a -e $_TGT ] && rm -f $_TGT    
done
for f in $(echo $@|xargs -r -n1 basename|sort -u); do
    if [ ! -s $_TOPDIR/$f ]; then
        echo -n "     "
        echo $"*ERROR: can't download rpm files."": $f"
        rm -rf $_TOPDIR
        exit 0
    fi
done

echo -n "     "
echo $"Rpm files downloaded successfully."

# move rpm to que directory and remove temporary diractory
mv -f $_TOPDIR/* $_QUEDIR
rm -rf $_TOPDIR

exit 0
