#!/usr/bin/env bash
#*******************************************************************************
# Copyright (c) 2023 Eclipse Foundation and others.
# This program and the accompanying materials are made available
# under the terms of the Eclipse Public License 2.0
# which is available at http://www.eclipse.org/legal/epl-v20.html
# SPDX-License-Identifier: EPL-2.0
#*******************************************************************************

# Bash strict-mode
set -o errexit
set -o nounset
set -o pipefail

IFS=$'\n\t'

SCRIPT_FOLDER="$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")"

service="${1:-}"
staging="${2:-}"

if [[ -z "${service}" ]]; then
  printf "ERROR: a service name must be given (e.g. 'blogs', 'newsroom', 'marketplace', 'projects', 'accounts','packages', 'www').\n"
  exit 1
fi

NAMESPACE="foundation-internal-webdev-${service}-eclipse-org"
PORT=8085

open_url() {
  local url=$1
  if which xdg-open > /dev/null; then # most Linux
    xdg-open "${url}"
  elif which open > /dev/null; then # macOS
    open "${url}"
  fi
}


if [[ "${staging}" == "staging" ]]; then
  pod_name="$(oc get pods -n "${NAMESPACE}" --no-headers=true | grep 'Running' | grep 'staging' | head -n 1 | awk '{print $1}')"
else
  pod_name="$(oc get pods -n "${NAMESPACE}" --no-headers=true | grep 'Running' | grep -v 'staging' | head -n 1 | awk '{print $1}')"
fi


echo "oc port-forward -n "${NAMESPACE}" "pod/${pod_name}" ${PORT}:8080"

oc port-forward -n "${NAMESPACE}" "pod/${pod_name}" ${PORT}:8080 &

bg_pid="$!"

cleanup() {
  printf "\nKilling background process %s" "${bg_pid}"
  kill "${bg_pid}"
}
trap cleanup EXIT

sleep 5

open_url "http://localhost:${PORT}"

wait "${bg_pid}"