#!/usr/bin/env bash

. /usr/share/dosis2/bin/shell-support-functions

enforce_root

OS="`getos`"
WHICH_REPO=""

echo_help() {
echo "prep-for-update [-h] [-s] [-l] -[-t]
-h | --help     show help
-s | --stable   set dosis-repo to stable (default) 
-l | --latest   set dosis-repo to latest
-t | --testing  set dosis-repo to testing
"
}


if [ "$1" = "" ]; then
	echo "No repo selected"
	echo_help
	exit 1
else
    case $1 in 
        -s | --stable )       shift
                            WHICH_REPO="-s"
                            ;;
        -l | --latest )     shift
                            WHICH_REPO="-l"
                            ;;
        -t | --testing )    shift
                            WHICH_REPO="-t"
                            ;;
        -h | --help )       echo_help
                            exit
                            ;;
        * )                 echo_help
                            exit 1
    esac
fi

/opt/dosis2/bin/change-dosis-repo "${WHICH_REPO}"

if [ "${OS}" = "Ubuntu" ]; then
	apt-get clean
	apt-get update

	retval=0
	for i in `seq 1 3`; do
		apt-get -y -d install dosis dosis-kiosk
		retval=$?
		if [ ${retval} = 0 ]; then
			break
		fi
	done
	
	exit ${retval}
elif [ "${OS}" = "CentOS" ]; then
	mkdir -p /var/lib/dosis2/rpm/archives
	rm -f /var/lib/dosis/rpm/archives/*.rpm
	yum clean all
	yum clean expire-cache

	retval=0
	for i in `seq 1 3`; do
		yum install -y --downloadonly --downloaddir=/var/lib/dosis2/rpm/archives dosis
		retval=$?
		if [ ${retval} = 0 ]; then
			break
		fi
	done

	exit ${retval}
else
	echo "Unsupported OS: ${OS}"
fi
