#!/bin/bash
# Solum Build Scirpt for Docker and lp-cedarish

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

##############################################################################
# tlog: Log text to stdout, and to the log file, with a datestamp
##############################################################################
function tlog () {
  TAG=`date +"%Y-%m-%d %H:%M:%S.%3N |"`
  echo "$TAG $1" | tee -a $LOG
}

##############################################################################
# run_timed_command: run a command with profiling, and set $EXIT_STATUS
##############################################################################
function run_timed_command () {
  if [ $EXIT_STATUS != "0" ] ; then
    tlog "Previous command failed. Exiting."
    exit 1
  fi
  START=`date +'%s'`
  CMD=$1
  tlog "Starting: $CMD"
  if [ "$SILENT" -eq "1" ] ; then
    $CMD 2>&1 >> /dev/null
    SILENT=0
  else
    $CMD 2>&1 | tee -a $LOG
  fi
  EXIT_STATUS=$?
  FINISH=`date +'%s'`
  let "ELAPSED = $FINISH - $START"
  if [ $EXIT_STATUS == "0" ] ; then
    tlog "Finished: $CMD [Elapsed: $ELAPSED sec]"
  else
    tlog "FAILED: $CMD [Elapsed: $ELAPSED sec] (EXIT_STATUS=$EXIT_STATUS)"
  fi
}

##############################################################################
# get_image_id: get the image_id for the image with the given name
##############################################################################
function get_image_id () {
  CMD="glance image-show $APP:latest"
  run_timed_command "$CMD" | awk '/^. id / { print $4; }'
}

##############################################################################
# print_end_timestamp: Print the elapsed tiem for the fulls cript execution
##############################################################################
function print_end_timestamp () {
  SCRIPT_FINISH=`date +'%s'`
  let "ELAPSED = $SCRIPT_FINISH - $SCRIPT_START"
  tlog "===== Total elapsed time: $ELAPSED sec"
}

##############################################################################
# Script Logic Begins Here
##############################################################################

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 [[ -z $1 ]] || [[ -z $2 ]] || [[ -z $3 ]] || [[ -z $4 ]]; then
  tlog "Usage:  build git_url appname project_id base_image"
  exit 1
fi

SILENT=1
run_timed_command "docker ps"
[[ $EXIT_STATUS != 0 ]] && tlog "cannot talk to docker." && exit 1

SILENT=1
run_timed_command "glance index"
if [ $EXIT_STATUS != 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

DOCKER_REGISTRY=${DOCKER_REGISTRY:-'127.0.0.1:5042'}
#BASE_DIR=/opt/solum
BASE_DIR=/dev/shm
#APP_DIR=$BASE_DIR/apps/$TENANT/$APP
GIT_CHECKSUM=$(echo $GIT | md5sum | awk '{print $1;}')
APP_DIR=$BASE_DIR/apps/$TENANT/$GIT_CHECKSUM
run_timed_command "mkdir -p $APP_DIR"

if [ -d "$APP_DIR/build" ] ; then
  cd $APP_DIR/build
  OUT=$(run_timed_command "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=$(get_image_id)
      if [ ${#image_id} == 36 ] ; then # uuid4 is 36 characters
        tlog "created_image_id=$image_id"
        print_end_timestamp
        exit 0
      fi
    fi
  fi
else
  run_timed_command "git clone $GIT $APP_DIR/build"
fi

# Build the application slug
tlog '===> Building App'
cd $APP_DIR/build
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)

run_timed_command "sudo docker attach $BUILD_ID"

cd $APP_DIR
run_timed_command "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
run_timed_command "sudo docker rm $BUILD_ID"
#run_timed_command "rm -rf $APP_DIR/build"

# 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 $DOCKER_REGISTRY/slugrunner
ADD slug.tgz /app
EXPOSE 5000
ENV port 5000
ENTRYPOINT ["/runner/init"]
CMD ["start","web"]
EOF

cd $APP_DIR
run_timed_command "sudo docker build -t $DOCKER_REGISTRY/$APP ."
run_timed_command "sudo docker push $DOCKER_REGISTRY/$APP"

image_id=$(get_image_id)

print_end_timestamp
tlog "created_image_id=$image_id"

exit 0
