#!/bin/bash
# Solum script for building custom languagepacks

SCRIPT_START_TIME=`date +'%s'`
LOG=${SOLUM_BUILD_LOG:="/opt/stack/logs/solum_build.log"}
REUSE_IMAGES_IF_REPO_UNCHANGED=${REUSE_IMAGES_IF_REPO_UNCHANGED:="1"}

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

# 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 Language Pack 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 6 ]; then
  TLOG Usage: $0 git_url lpname project_id [base_image] [git_private_key] lp_metadata
  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
LPNAME=$1
shift
TENANT=$1
shift
BASE_IMAGE=$1
shift
GIT_PRIVATE_KEY=$1
shift
LP_METADATA=$1
shift

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

TLOG ===== Cloning repo
PRUN git clone $GIT $APP_DIR/build

if [ -d "$APP_DIR/build" ] ; then
  cd $APP_DIR/build
  PRUN sudo docker build -t $LPNAME .
  TLOG ===== finished docker build
  sudo docker save "$LPNAME" | glance image-create --container-format=docker --disk-format=raw --name "$LPNAME"
  TLOG ===== finished uploading to glance
fi

image_id=$(app_glance_id $LPNAME)

# Tag the glance image as a solum language pack
TLOG ===== tagging glace image $image_id
glance --os-image-api-version 2 image-tag-update $image_id 'solum::lp'
glance --os-image-api-version 2 image-tag-update $image_id $LP_METADATA

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

TLOG created_image_id=$image_id

# We don't set created_image_id so that
# the deploy step is skipped in workers/handlers/shell.py
# echo created_image_id=$image_id

exit 0
