#!/usr/bin/env bash
# THIS FILE IS PART OF THE CYLC WORKFLOW ENGINE.
# Copyright (C) NIWA & British Crown (Met Office) & Contributors.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

set -eu

if [[ ${HOST_HOSTNAME} == false ]]; then
    # if HOST_HOSTNAME is false then do nothing
    exit 0
fi

get_ip_addr () {
    local HOST="$1"
    ping "$HOST" -c 1 | sed -n "s/PING $HOST (\([0-9\.]*\)).*/\1/p"
}

map_ip_addr () {
    local HOST="$1"
    local ADDR="$2"
    echo -e "$ADDR\t$HOST" >> /etc/hosts
}

alias_hostname () {
    # configure one hostname to point at the same IP as another
    local FROM="$1"  # source
    local TO="$2"  # target
    map_ip_addr "$FROM" "$(get_ip_addr "$TO")"

}

# map the hostname of the docker host (the host that is running the container)
# onto whatever 'host.docker.internal' points to
# NOTE:
#   * for Mac OS and Windows 'host.docker.internal' is set by docker desktop
#   * for Linux you must set it yourself using the --add-host run arg
alias_hostname "$HOST_HOSTNAME" 'host.docker.internal'
