#!/bin/bash

GENERATORS_DIR=$(dirname "$0")
. $GENERATORS_DIR/echo2-function

if [ -z $1 ]; then
    >&2 echo2 "[  ERROR  ]: Specify as first parameter the full path of the app context directory."
    exit -1
fi

if [ -z $1 ]; then
    >&2 echo2 "[  ERROR  ]: Specify as second parameter the dockerhub username."
    exit -1
fi

if [ ! -d $1 ]; then
    >&2 echo2 "[  ERROR  ]: The path of the context dir '$1' couldn't be reached."
    exit -1
fi

BASE_IMAGE_NAME="compss/compss:1.3"

ABS_CONTEXT=$1
USERNAME=$2
CONTAINER_SUFFIX=$(echo $(basename $ABS_CONTEXT) | tr '[:upper:]' '[:lower:]')
APP_IMAGE_NAME="$USERNAME/compss-$CONTAINER_SUFFIX"
APP_IMAGE_NAME_AND_TAG="${APP_IMAGE_NAME}:latest"


>&2 echo2 "Generating Dockerfile..."

echo -e "\
FROM $BASE_IMAGE_NAME
RUN mkdir -p $ABS_CONTEXT \
    yes yes | ssh-keygen -f /root/.ssh/id_rsa -t rsa -N '' > /dev/null ; \
    cat /root/.ssh/id_rsa.pub > /root/.ssh/authorized_keys
ADD . "$ABS_CONTEXT"
"                                                               > $ABS_CONTEXT/Dockerfile
    
>&2 echo2 "Building application image '$APP_IMAGE_NAME'..."

# First create, to be able to use cache
>&2 docker build --tag="$APP_IMAGE_NAME_AND_TAG" "$ABS_CONTEXT"

# Then erase the image created and tagged as latest, which would be a former image created by this script...

if [ ! $? -eq 0 ]; then
    >&2 echo2 "There was a problem creating the image"
    exit -1
fi

>&2 echo

echo "${APP_IMAGE_NAME_AND_TAG}"  #OUTPUT THE IMAGE NAME!

exit 0