#!/bin/bash

UPDATEVM=`qvm-get-updatevm`
if [ -z "$UPDATEVM" ]; then
    echo "UpdateVM not set, exiting"
    exit 1
fi

if [ "$1" = "--help" ]; then
    echo "This tool is used to download packages for dom0. Without package list"
    echo "it checks for updates for installed packages"
    echo ""
    echo "Usage: $0 [--clean] [<pkg list>]"
    echo "    --clean      clean yum cache before doing anything"
    echo "    <pkg list>   download (and install if run by root) new packages"
    echo "                 in dom0 instead of updating"
    exit
fi

# We should ensure the clocks in Dom0 and UpdateVM are in sync
# becuase otherwise yum might complain about future timestamps
qvm-sync-dom0-clock

echo "Checking for dom0 updates"

# Start VM if not running already
qvm-run -a $UPDATEVM true || exit 1
/usr/lib/qubes/sync_rpmdb_updatevm.sh || exit 1
qvm-run --pass_io $UPDATEVM "/usr/lib/qubes/qubes_download_dom0_updates.sh --doit --nogui $*" || exit 1
# Wait for download completed
while pidof -x qubes-receive-updates >/dev/null; do sleep 0.5; done
PKGS=
OPTS=
# Filter out some yum options and collect packages list
while [ $# -gt 0 ]; do
    case "$1" in
        --enablerepo=*|\
        --disablerepo=*|\
        --clean)
            ;;
        -*)
            OPTS="$OPTS $1"
            ;;
        *)
            PKGS="$PKGS $1"
            ;;
    esac
    shift
done

if [ "x$PKGS" != "x" ]; then
    ID=$(id -ur)
    if [ $ID != 0 ] ; then
        echo "This script should be run as root, use sudo next time."
        echo "Now you can manually run yum install (use sudo again)."
        exit
    fi

    yum $OPTS install $PKGS
elif [ -f /var/lib/qubes/updates/repodata/repomd.xml ]; then
    # Above file exists only when at least one package was downloaded
    yum check-update
    if [ $? -eq 100 ]; then

        ID=$(id -ur)
        if [ $ID != 0 ] ; then
            echo "This script should be run as root, use sudo next time."
            echo "Now you can manually run yum update (use sudo again)."
            exit
        fi
        yum $OPTS update
    fi
else
    echo "No updates avaliable"
fi