echo "--- Building QMI Cloud docker images for branch $CI_COMMIT_REF_NAME"

export VERSION_APP=$(cat package.json | grep version | head -1 | awk -F: '{ print $2 }' | sed 's/[",]//g' | tr -d '[[:space:]]')
export VERSION_WORKER=$(cat qmi-cloud-worker/package.json | grep version | head -1 | awk -F: '{ print $2 }' | sed 's/[",]//g' | tr -d '[[:space:]]')
export VERSION_CLI=$(cat qmi-cloud-cli/package.json | grep version | head -1 | awk -F: '{ print $2 }' | sed 's/[",]//g' | tr -d '[[:space:]]')

export TAG_APP=$VERSION_APP
export TAG_WORKER=$VERSION_WORKER
export TAG_CLI=$VERSION_CLI
export STABLE_TAG="latest"

if [ "$CI_COMMIT_REF_NAME" != "master" ]; then 
    TAG_APP="$VERSION_APP-$CI_COMMIT_REF_NAME"
    TAG_WORKER="$VERSION_WORKER-$CI_COMMIT_REF_NAME"
    TAG_CLI="$VERSION_CLI-$CI_COMMIT_REF_NAME"
    STABLE_TAG="latestdev"
fi

echo "$DOCKER_REGISTRY_PASSWORD" | docker login --username "$DOCKER_REGISTRY_USER" --password-stdin

echo "--- Building image: qlikgear/qmi-cloud-cli:$TAG_CLI"
docker build -f ./qmi-cloud-cli/Dockerfile -t qlikgear/qmi-cloud-cli:$TAG_CLI ./
echo "--- Pushing image: qlikgear/qmi-cloud-cli:$TAG_CLI"
docker push qlikgear/qmi-cloud-cli:$TAG_CLI
docker image tag qlikgear/qmi-cloud-cli:$TAG_CLI qlikgear/qmi-cloud-cli:$STABLE_TAG 
#docker build -f ./qmi-cloud-cli/Dockerfile -t qlikgear/qmi-cloud-cli:$STABLE_TAG ./
docker push qlikgear/qmi-cloud-cli:$STABLE_TAG


echo "--- Building image: qlikgear/qmi-cloud-worker:$TAG_WORKER"
docker build -f ./qmi-cloud-worker/Dockerfile -t qlikgear/qmi-cloud-worker:$TAG_WORKER ./
echo "--- Pushing image: qlikgear/qmi-cloud-worker:$TAG_WORKER"
docker push qlikgear/qmi-cloud-worker:$TAG_WORKER
docker image tag qlikgear/qmi-cloud-worker:$TAG_WORKER qlikgear/qmi-cloud-worker:$STABLE_TAG 
#docker build -f ./qmi-cloud-worker/Dockerfile -t qlikgear/qmi-cloud-worker:$STABLE_TAG ./
docker push qlikgear/qmi-cloud-worker:$STABLE_TAG

echo "--- Building image: qlikgear/qmi-cloud-app:$TAG_APP"
docker build -f ./Dockerfile -t qlikgear/qmi-cloud-app:$TAG_APP ./
echo "--- Pushing image: qlikgear/qmi-cloud-app:$TAG_APP"
docker push qlikgear/qmi-cloud-app:$TAG_APP
docker image tag qlikgear/qmi-cloud-app:$TAG_APP qlikgear/qmi-cloud-app:$STABLE_TAG
#docker build -f ./Dockerfile -t qlikgear/qmi-cloud-app:$STABLE_TAG ./
docker push qlikgear/qmi-cloud-app:$STABLE_TAG
