#!/bin/bash
#
# Copyright 2018 Istio Authors. All Rights Reserved.
#
# 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.
#
################################################################################
#

WD=$(dirname "$0")
WD=$(cd "$WD" && pwd)

function usage() {
  [[ -n "${1}" ]] && echo "${1}"

  cat <<EOF
usage: ${BASH_SOURCE[0]} [options ...]"
  options:
    -a ... backend address
    -c ... envoy config file path
    -e ... envoy binary path
    -l ... debug level
    -m ... mixer server address
    -p ... listening port
    -t ... envoy config template file path
EOF
  exit 2
}

TEMPLATE="${WD}/envoy.conf.template"
CONFIG="${WD}/envoy.conf"
DEBUG=''

PORT='9090'
MIXER_SERVER='localhost:9091'
BACKEND='localhost:8080'

while getopts :a:c:e:l:m:p:t: arg; do
  case ${arg} in
    a) BACKEND="${OPTARG}";;
    c) CONFIG="${OPTARG}";;
    e) ENVOY="${OPTARG}";;
    l) DEBUG="-l ${OPTARG}";;
    m) MIXER_SERVER="${OPTARG}";;
    p) PORT="${OPTARG}";;
    t) TEMPLATE="${OPTARG}";;
    *) usage "Invalid option: -${OPTARG}";;
  esac
done

sed -e "s|\${PORT}|${PORT}|g" \
    -e "s|\${BACKEND}|${BACKEND}|g" \
    -e "s|\${MIXER_SERVER}|${MIXER_SERVER}|g" \
    "${TEMPLATE}" > "${CONFIG}"

"${ENVOY}" -c "${CONFIG}" "${DEBUG}"

