#! /bin/sh
# zypper-download
# Yum does have a download cache, but it does not download source rpms,
# and zypper is preferred.
# See: #348733 - zypper should have --download-only and --cache options

RPM_CACHE=${RPM_CACHE-/var/cache/zypp/archives}

if test $# -eq 0 -o "$1" = '-h' -o "$1" = "--help"; then
    cat 1>&2 <<EOF
Usage: zypper-download [--download-only] [source] PACKAGE-NAME...

Crude script to download [source] rpms and cache them in $RPM_CACHE.
EOF
    exit 2
fi

if test "$1" = "-d" -o "$1" = "--download-only"; then
    ZYPPER_DOWNLOAD_ONLY=yes
    shift;
fi

yesforce=-yf
if test "$1" == "source"; then
    source=$1-
    yesforce=
    shift;
fi

caching_rpm=/usr/local/bin/rpm
cat > $caching_rpm <<EOF
#! /bin/sh
LANG=C
log=/tmp/zypper-download.log
date "+%b %e %T" | tr -d '\n' >> \$log
echo -n : >> \$log
last=\$(eval echo '\$'{\$#})
#echo "last:\$last" >> /tmp/zypper-download.log
#echo "all:\$@" >> /tmp/zypper-download.log
if test -n "\$last" && echo \$last | grep /var/adm/mount/AP_0x; then
    mkdir -p $RPM_CACHE
    cp -pv \$last $RPM_CACHE
    echo -n caching \$(basename \$last) >> \$log
fi
if test -z "\$ZYPPER_DOWNLOAD_ONLY"; then
    exec /bin/rpm "\$@"
fi
echo >> \$log
EOF
chmod +x $caching_rpm

export ZYPPER_DOWNLOAD_ONLY
zypper -n ${source}install ${yesforce} "$@"
#rm -f $caching_rpm
