#!/bin/bash

docker ps 2> /dev/null > /dev/null
[[ $? != 0 ]] && echo "cannot talk to docker." && exit 1

# tool that calls this has specific variabes,  even though
# we don't use base image, it still has an arg that we need
# to shift out.
if [[ -z $1 ]] || [[ -z $2 ]] || [[ -z $3 ]] || [[ -z $4 ]]; then
  echo "Usage:  build git_url appname project_id base_image"
  exit 1
fi

GIT=$1
shift
APP=$1
shift
TENANT=$1
shift
BASE_IMAGE=$1
shift

DOCKER_REGISTRY=${DOCKER_REGISTRY:-'127.0.0.1:5042'}

if [[ -z $OS_USERNAME ]]; then
  echo 'openstack credentials not passed via ENV. hunting for openrc.'
  [[ -f ./openrc ]] && . ./openrc
  [[ -f ~/devstack/openrc ]] && . ~/devstack/openrc
fi

APP_DIR=/opt/solum/apps/$TENANT/$APP
mkdir -p $APP_DIR

[[ -d $APP_DIR/build ]] && rm -rf $APP_DIR/build
git clone $GIT $APP_DIR/build

echo '===> building App'

cd $APP_DIR/build

sudo docker build -t $DOCKER_REGISTRY/$APP .

sudo docker push $DOCKER_REGISTRY/$APP

image_id=$(glance image-show $APP:latest | grep " id " | cut -d"|" -f3 | tr -d " ")

echo "created_image_id=$image_id"

exit 0
