#!/usr/bin/env bash

set -e

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

BASE_DIR="$TAMARIN_DIR" source "$TAMARIN_DIR/lib/util.sh"

function show_usage {
  echo
  echo "Usage: $0 -p project_path [-a arch] [-d destination] [-i image] [-k]"
  echo
  echo "Parameters: "
  echo
  echo "  -p Path to the project to build"
  echo "  -a Optional : Target architecture (default amd64)"
  echo "  -o Optional : Default options file to load (default none)"
  echo "  -d Optional : Destination of the builed packages (default ./packages)"
  echo "  -i Optional : Name of the Docker image to use for build (default: debian:jessie)"
  echo "  -k Optional : Keep the Docker container after build "
  echo "  -B Optional : Build branch (for git projects only) (default dist/ubuntu/precise/master)"
  echo
  exit 2
}

# Create a build container based on the $BASE_IMAGE argument
function create_container {

  # Escape image name
  local 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
  local temp_dir="$(mktemp -d)"

  local projectName=${1}

  # Link lib & hooks folders
  ln -s $(readlink -f "$TAMARIN_DIR/lib") "$temp_dir/lib"
  ln -s $(readlink -f "$TAMARIN_DIR/hooks") "$temp_dir/hooks"

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

    ENV DEBIAN_FRONTEND noninteractive

    RUN apt-get update &&\
        apt-get install --yes --no-install-recommends build-essential devscripts equivs

    RUN mkdir /root/.tamarin
    RUN mkdir /project

    ADD ./lib /root/.tamarin/lib
    ADD ./hooks /hooks
    RUN chmod +x /root/.tamarin/lib/build.sh

    VOLUME /src
    VOLUME /dist

EOF

  # Add default opts file if defined
  if [[ -e "${DEFAULT_OPTS}" ]]; then
    ln -s "${DEFAULT_OPTS}" "$temp_dir/default_opts"
    echo "ADD ./default_ops /tmp/tamarin/default_opts" >> "$temp_dir/Dockerfile"
  fi

  exec_hooks "containerbuild" "$temp_dir"

  echo "CMD /root/.tamarin/lib/build.sh ${projectName} ${BUILD_BRANCH} /tmp ${BUILD_TAG}" >> "$temp_dir/Dockerfile"

  # Build image
  tar -C "$temp_dir" -czh . | docker build -t "$container_tag" - 2> >(stderr) 1> >(stdout)

  # Delete temporary folder
  rm -rf "$temp_dir"

}

# Main function
function main {

  info "Building container from $BASE_IMAGE..."

  local project_name=$(basename ${PROJECT_PATH})

  # Create container & "$container_tag" variable
  create_container ${project_name}

  local docker_opt="run -e \"DISTRIB=$BASE_IMAGE\" -e \"PROJECT_NAME=$project_name\""

  # Expose host uid & gid
  docker_opt="${docker_opt}  -e HOST_UID=$(id -u)  -e HOST_GID=$(id -g)"

  # Expose host proxy variables
  docker_opt="${docker_opt} -e HTTP_PROXY=${HTTP_PROXY} -e HTTPS_PROXY=${HTTPS_PROXY}"
  docker_opt="${docker_opt} -e http_proxy=${http_proxy} -e https_proxy=${https_proxy}"

  # Target architecture
  docker_opt="${docker_opt} -e TARGET_ARCH=${TARGET_ARCH}"

  if [[ ${PERSIST_CONTAINER} -eq 0 ]]
  then
    docker_opt="${docker_opt} --rm "
  else
    docker_opt="${docker_opt}"
  fi

  docker_opt="${docker_opt} -v=\"$PROJECT_PATH:/src:ro\" -v=\"$PROJECT_DEST:/dist:rw\" $container_tag"

  info "Switching to container..."
  debug "docker ${docker_opt}"
  docker ${docker_opt}
  res=${?}

  success "Done"
  return ${res}
}

#
# Parsing options
#
while getopts "kp:d:i:B:t:a:o:" option
do
  case $option in
    k)
      PERSIST_CONTAINER=1
      ;;
    p)
      PROJECT_PATH=$(readlink -f ${OPTARG})
      ;;
    d)
      PROJECT_DEST=$(readlink -f ${OPTARG})
      ;;
    i)
      BASE_IMAGE="${OPTARG}"
    ;;
    B)
      BUILD_BRANCH=${OPTARG}
    ;;
    t)
      BUILD_TAG=${OPTARG}
    ;;
    a)
      TARGET_ARCH=${OPTARG}
    ;;
    o)
      DEFAULT_OPTS=$(readlink -f ${OPTARG})
    ;;
    *)
      show_usage
    ;;
  esac
done

[[ -z ${PROJECT_PATH} ]] && show_usage
[[ -z ${PROJECT_DEST} ]] && PROJECT_DEST=$(readlink -f "./packages")
[[ -z ${BASE_IMAGE}   ]] && BASE_IMAGE="debian:jessie"
[[ -z ${BUILD_BRANCH} ]] && BUILD_BRANCH="dist/ubuntu/precise/master"
[[ -z ${PERSIST_CONTAINER} ]] && PERSIST_CONTAINER=0
[[ -z ${TARGET_ARCH} ]] && TARGET_ARCH=amd64

#
# Warn user about "proxy"
#

if [[ -n ${http_proxy} ]]
then
  warn "You have a proxy defined please make sure docker deamon is configured to use this proxy"
fi

main