#!/bin/bash
#
# The MIT License (MIT)
# Copyright © 2016 Michał Dobaczewski <mdobak@gmail.com>
#

_HOSTS_SH=1

# Builds the /etc/hosts configuration file. The configuration file will maps the
# Docker containers names to thiers IPs.
hosts_build_file ()
{
  local _HOSTS="";

  for VM in `docker ps|tail -n +2|awk '{print $NF}'`; do
    local IP=$(docker inspect --format '{{ .NetworkSettings.IPAddress }}' $VM);

    if [[ -z $(docker inspect --format '{{ .Config.Domainname }}' $VM 2> /dev/null) ]]; then
      local HOSTNAME=$(docker inspect --format '{{ .Config.Hostname }}' $VM);
    else
      local HOSTNAME=$(docker inspect --format '{{ .Config.Hostname }}.{{ .Config.Domainname }}' $VM);
    fi

    _HOSTS="$_HOSTS$IP $HOSTNAME # Generated by docker-dev-env\n";
  done

  echo $_HOSTS
}

# Append a configuration for the /etc/hosts file from the hosts_build_file
# function on the host OS.
hosts_setup_on_host ()
{
  local HOSTS=$(hosts_build_file)

  sed -i .bak "/# Generated by docker-dev-env/d" /etc/hosts
  printf "$HOSTS" >> /etc/hosts
}

# Append a configuration for the /etc/hosts file from the hosts_build_file
# function on the host OS.
#
# $1 - Setup only containers created by this script. $true/$false.
hosts_setup_on_containers ()
{
  local SETUP_ONLY_DEV_ENV_CONTAINERS=$1
  local HOSTS=$(hosts_build_file)

  for VM in `docker ps|tail -n +2|awk '{print $NF}'`; do
    if [[ $SETUP_ONLY_DEV_ENV_CONTAINERS == $true ]] && ! docker_is_dev_env_container $VM; then
      continue;
    fi

    local CONTAINER_CMD="printf '$HOSTS' >> /etc/hosts"
    local DOCKER_CMD="/bin/sh -c \"$CONTAINER_CMD\""

    echo_log "Configuring the /etc/hosts file for the \"$VM\" machine"
    docker exec $VM /bin/sh -c "sed '/# Generated by docker-dev-env/d' /etc/hosts > /etc/hosts_tmp; cat /etc/hosts_tmp > /etc/hosts"
    eval "docker exec $VM $DOCKER_CMD"
  done
}
