#!/bin/bash -e

# Build and Package (docker image) Memgraph

function print_help () {
    echo "Usage: $0 [--latest] MEMGPRAH_PACKAGE.deb"
    echo "Optional arguments:"
    echo -e "  -h|--help           Print help."
    echo -e "  --latest            Tag image as latest version."
}

working_dir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

latest_image=""
tag_latest=""
if [[ $# -eq 2 && "$1" == "--latest" ]]; then
  latest_image="memgraph:latest"
  tag_latest="-t memgraph:latest"
  shift
elif [[ $# -ne 1 || "$1" == "-h" || "$1" == "--help" ]]; then
  print_help
  exit 1
fi

if [[ ! -f "$1" ]]; then
  echo "File '$1' does not exist!"
  exit 1
fi

# Copy the .deb to working directory.
cp "$1" "${working_dir}/"

cd ${working_dir}
# Extract version from deb name
deb_name=`echo $(basename $1) | sed 's/.deb//'`
version=`echo ${deb_name} | sed 's/.*[-_]\(.*\)-.*/\1/'`
image_name="memgraph:${version}"
package_name="memgraph-${version}-docker.tar.gz"
# Build docker image.
docker build -t ${image_name} ${tag_latest} -f ${working_dir}/memgraph.dockerfile --build-arg deb_release=${deb_name}.deb .
docker save ${image_name} ${latest_image} > ${package_name}
rm -rf "${deb_name}.deb"
echo "Built Docker image at '${working_dir}/${package_name}"
