#!/bin/bash
# Copyright 2014 - Rackspace Hosting
#
#    Licensed under the Apache License, Version 2.0 (the "License");
#    you may not use this file except in compliance with the License.
#    You may obtain a copy of the License at
#
#        http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS,
#    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#    See the License for the specific language governing permissions and
#    limitations under the License.


# Solum Build Script for Docker and lp-cedarish

SCRIPT_START_TIME=$(date +"%s")

PROJECT_ID=${PROJECT_ID:-null}
BUILD_ID=${BUILD_ID:-null}
TASKNAME=build
REUSE_IMAGES_IF_REPO_UNCHANGED=${REUSE_IMAGES_IF_REPO_UNCHANGED:="1"}
USER_PARAMS=${USER_PARAMS:-null}
SOLUM_PARAMS=${SOLUM_PARAMS:-null}

# TLOG, PRUN, etc. defined in common/utils
HERE=$(dirname $0)
source $HERE/../../common/utils

LOG_FILE=$(GET_LOGFILE)

# Get the image_id of the image named $1
function app_glance_id () {
  glance image-list --name $1 --sort-key updated_at --sort-dir asc | grep -v "+--" | tail -1 | cut -d'|' -f2
}

TLOG ===== Starting Build Script $0 $*

# Make sure tenant auth credentials were passed in.
if [[ -z "$OS_AUTH_TOKEN" ]]; then
  TLOG OpenStack credentials not passed via ENV.
  exit 1
fi

# Check command line arguments
if [ $# -lt 4 ]; then
  TLOG Usage: $0 git_url appname project_id base_image [git_private_key]
  exit 1
fi

PRUN silent docker ps
[[ $? != 0 ]] && TLOG cannot talk to docker. && exit 1

PRUN silent glance image-list
if [ $? != 0 ]; then
  TLOG Cannot talk to Glance. Check your OpenStack credentials. && exit 1
fi

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

BASE_DIR=/dev/shm
GIT_CHECKSUM=$(echo $GIT | md5sum | awk '{print $1;}')
APP_DIR=$BASE_DIR/apps/$TENANT/$GIT_CHECKSUM
PRUN silent mkdir -p $APP_DIR
add_ssh_creds "$GIT_PRIVATE_KEY" "$APP_DIR"

if ! (test_public_repo $GIT); then
    TLOG Could not reach $GIT with curl. Failing.
    exit 1
fi

if [ -d "$APP_DIR/build" ] ; then
  cd $APP_DIR/build
  OUT=$(git pull | grep -c 'Already up-to-date')
  # Check to see if this is the same as last build, and don't rebuild if allowed to skip
  if [ "$OUT" != "0" ] ; then
    if [ "$REUSE_IMAGES_IF_REPO_UNCHANGED" -eq "1" ] ; then
      image_id=$(app_glance_id $APP)
      if [ ${#image_id} == 36 ] ; then # uuid4 is 36 characters
        TLOG Repo is unchanged. Reusing image $image_id.
        TLOG created_image_id=$image_id
        # Need stdout for solum-worker to parse the image_id
        echo created_image_id=$image_id
        TOTAL_TIME=$(elapsed $SCRIPT_START_TIME)
        TLOG ===== Total elapsed time: $TOTAL_TIME sec
        exit 0
      fi
    fi
  fi
else
  PRUN git clone $GIT $APP_DIR/build
fi


# Build the application slug
TLOG "===>" Building App
cd $APP_DIR/build
COMMIT_ID=$(git log -1 --pretty=%H)
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  \
           solum/slugbuilder)

PRUN sudo docker logs --tail=all -f $BUILD_ID

cd $APP_DIR
PRUN sudo docker cp $BUILD_ID:/tmp/slug.tgz $APP_DIR/
if [ ! -f "$APP_DIR/slug.tgz" ] ; then
  TLOG Slug build failed see container: $BUILD_ID
  exit
fi
PRUN sudo docker rm $BUILD_ID
remove_ssh_creds "$GIT_PRIVATE_KEY"

# copy params to the working dir
mkdir $APP_DIR/params
if [[ $USER_PARAMS != null ]]; then
  cp $USER_PARAMS $APP_DIR/params/user_params
fi
if [[ $SOLUM_PARAMS != null ]]; then
  cp $SOLUM_PARAMS $APP_DIR/params/solum_params
fi

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

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

cd $APP_DIR
PRUN sudo docker build -t $APP .
sudo docker save "$APP" | glance image-create --container-format=docker --disk-format=raw --name "$APP" > /dev/null

image_id=$(app_glance_id $APP)

TOTAL_TIME=$(elapsed $SCRIPT_START_TIME)
TLOG ===== Total elapsed time: $TOTAL_TIME sec

TLOG created_image_id=$image_id

# Need stdout for solum-worker to parse the image_id
echo created_image_id=$image_id

exit 0
