#!/usr/bin/env bash

DIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )
source "$DIR/lib/util.sh"

function show_usage {
  echo
  echo "Usage: $0 <deb_file> <image>"
  echo
  echo "Paramètres: "
  echo
  echo "  - <deb_file> Chemin vers le paquet Debian dont on doit vérifier l'installation"
  echo "  - <image> Nom de l'image Docker à utiliser comme environnement pour tester l'installation"
  echo
}

function create_container {

  # Escape image name
  escaped_basename=$(echo "$BASE_IMAGE" | sed 's/[^a-z0-9\-\_\.]/\_/gi')
  # Generate container tag
  container_tag="tamarin:${escaped_basename}_$(date +%s)"
  # Create temporary dir for the Dockerfile
  temp_dir="$(mktemp -d)"

  # Link lib folder
  ln -s $(readlink -f "$DIR/lib") "$temp_dir/lib"

  # Create Dockerfile
  cat << EOF > "$temp_dir/Dockerfile"
    FROM $BASE_IMAGE

    ENV DEBIAN_FRONTEND noninteractive

    RUN apt-get update && apt-get install --yes gdebi-core lintian

    ADD ./lib /root/.tamarin
    RUN chmod +x /root/.tamarin/install.sh

    VOLUME /deb

    ENTRYPOINT ["/root/.tamarin/install.sh"]

EOF

  # Build image
  tar -C "$temp_dir" -czh . | docker build -t "$container_tag" - 1>&2

  # Delete temporary folder
  rm -rf "$temp_dir"

  # Return newly created container's tag
  echo $container_tag

}

function main {

  # Create container image
  container_tag=$(create_container)

  # Run container and install package
  docker run -e "DISTRIB=$BASE_IMAGE" --rm -v="$DEB_DIR:/deb" "$container_tag" "/deb/$DEB_NAME"

  # Check for return
  if [ $? != 0 ]; then
    fatal "Installation did not complete correctly !"
  fi

  info "Installation complete."

}

# Test for arguments
if [ -z "$1" ] || [ -z "$2" ]; then
  show_usage
  exit 1
fi

DEB_PATH=$(readlink -f "$1")
DEB_NAME=$(basename "$DEB_PATH")
DEB_DIR=$(dirname "$DEB_PATH")
BASE_IMAGE="$2"

main