#!/bin/bash -xe

PLUGIN=$1
PLUGIN_VERSION=${2:-''}
PLUGIN_DISTRO=${3:-''}

export DIB_MIN_TMPFS=10

# build a specific version if requested
if [ -n "${PLUGIN}" ] && [ -n "${PLUGIN_VERSION}" ] && [ -n "${PLUGIN_DISTRO}" ]; then
    case ${PLUGIN} in
        vanilla|cloudera|ambari)
            VERSION_FLAG="-v ${PLUGIN_VERSION}"
            ;;
        mapr)
            VERSION_FLAG="-r ${PLUGIN_VERSION}"
            ;;
        spark)
            VERSION_FLAG="-s ${PLUGIN_VERSION}"
            ;;
        storm)
            VERSION_FLAG="-t ${PLUGIN_VERSION}"
            ;;
        *)
            VERSION_FLAG=""
            ;;
    esac
    tox -e venv -- sahara-image-create -x -u -p ${PLUGIN} -i ${PLUGIN_DISTRO} ${VERSION_FLAG}
    exit
fi

# build (almost) all versions for a specified plugin
case "$PLUGIN" in
    "vanilla")
        # temporary don't test building fedora image
        for distro in ubuntu centos7; do
            # limit to 4 releases
            for version in 2.7.1 2.7.5 2.8.2 3.0.1; do
                tox -e venv -- sahara-image-create -x -u -p $PLUGIN -i $distro -v $version
            done
        done
        ;;
    "cloudera")
        # manually call each distro for cloudera, so we can cleanup
        # cache and generated images from the previous run
        # (saving space a bit)
        for distro in ubuntu centos7; do
            # NOTE(vgridnev): Number of versions are growing; testing only 2 latest
            # releases of CDH
            for version in 5.9 5.11; do
              tox -e venv -- sahara-image-create -x -u -p $PLUGIN -i $distro -v $version
              find . -maxdepth 1 -name '*cloudera*.qcow2' -delete
              sudo rm -rf ~/.cache/image-create
            done
        done
        ;;
    *)
        tox -e venv -- sahara-image-create -x -u -p $PLUGIN
        ;;
esac
