#!/bin/bash

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

if [[ -z $1 ]] || [[ -z $2 ]] || [[ -z $3 ]]; then
  echo "Usage:  build git_url appname project_id"
  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

cd $APP_DIR/build

echo '===> building App'

# Build the application slug
BUILD_ID=$(git archive master | sudo docker run -i -a stdin \
           -v /opt/solum/cache:/tmp/cache:rw  \
           -v /opt/solum/buildpacks:/tmp/buildpacks:rw  \
           $DOCKER_REGISTRY/slugbuilder)

sudo docker attach $BUILD_ID

cd $APP_DIR
sudo docker cp $BUILD_ID:/tmp/slug.tgz $APP_DIR/
sudo docker rm $BUILD_ID
rm -rf $APP_DIR/build

# Build the application image by injecting slug into runner
# and push to docker-registry ( which is tied to glance )

cat << EOF > $APP_DIR/Dockerfile
# SOLUM APP BUILDER
FROM $DOCKER_REGISTRY/slugrunner
ADD slug.tgz /app
EXPOSE 5000
ENV port 5000
ENTRYPOINT ["/runner/init"]
CMD ["start","web"]
EOF

cd $APP_DIR
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
