#!/usr/bin/env bash
# -*- coding: utf-8 -*-
# -*- mode: shell -*-

# (c) Copyright 2014 WibiData, Inc.
#
# See the NOTICE file distributed with this work for additional
# information regarding copyright ownership.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# ------------------------------------------------------------------------------

# This script updates the /etc/hosts file with an entry for a newly created or
# started bento. Modifying /etc/hosts requires root access, therefore running
# this script will prompt for a password (and the user must have sudoer
# permissions).

# Usage:
#
#   $ update-etc-hosts <IP address> <host name>
#

# ------------------------------------------------------------------------------

set -o nounset   # Fail when referencing undefined variables
set -o errexit   # Script exits on the first error
set -o pipefail  # Pipeline status failure if any command fails
if [[ ! -z "${DEBUG:-}" ]]; then
  source=$(basename "${BASH_SOURCE}")
  PS4="# ${source}":'${LINENO}: '
  set -x
fi

# ------------------------------------------------------------------------------

address=$1
host=$2

if [[ $address != 172.17.* ]]; then
  echo "Invalid address: '${address}'. Must be be in the 172.17.0.0/16 subnet." 1>&2
  exit 1;
fi

temp=$(mktemp /tmp/hosts.tmp.XXXXXX)

cat /etc/hosts | grep --invert-match "\s${host}$" > $temp
echo "${address}	${host}" >> $temp
sudo cp $temp /etc/hosts
