#!/bin/bash -e

# Build and package Docker image of Memgraph.

function print_help () {
    echo "Usage: $0 [--latest] MEMGRAPH_PACKAGE.(deb|rpm)"
    echo "Optional arguments:"
    echo -e "\t-h|--help\t\tPrint help."
    echo -e "\t--latest\t\tTag 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

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

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

extension="${package_path##*.}"

if [[ "$extension" == "deb" ]]; then
  # Extract version and offering from deb name.
  package_name=`echo $(basename "$package_path") | sed 's/.deb$//'`
  version=`echo ${package_name} | cut -d '_' -f 2 | rev | cut -d '-' -f 2- | rev | tr '+~' '__'`
  dockerfile_path="${working_dir}/memgraph_deb.dockerfile"
elif [[ "$extension" == "rpm" ]]; then
  # Extract version and offering from deb name.
  package_name=`echo $(basename "$package_path") | sed 's/.rpm$//'`
  version=`echo ${package_name} | cut -d '-' -f 2 | rev | cut -d '-' -f 2- | rev`
  version=${version%_1}
  dockerfile_path="${working_dir}/memgraph_rpm.dockerfile"
else
  echo "Invalid file sent as the package"
  print_help
  exit 1
fi

image_name="memgraph:${version}"
image_package_name="memgraph-${version}-docker.tar.gz"

# Build docker image.
# NOTE: --pull is here to always pull that latest base image because of security patches.
docker build --pull -t ${image_name} ${tag_latest} -f ${dockerfile_path} \
--build-arg BINARY_NAME=${package_name} \
--build-arg EXTENSION=${extension} \
--build-arg TARGETARCH="" .
docker save ${image_name} ${latest_image} | gzip > ${image_package_name}
rm "${package_name}.${extension}"
echo "Built Docker image at '${working_dir}/${image_package_name}'"
