#!/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:-}"
local_path="${3:-}"
remote_path="${4:-}"

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

namespace="foundation-internal-webdev-${service}-eclipse-org"

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

#copy files to the remote server.4
echo "oc cp "${local_path}" "${namespace}"/"${pod_name}":/tmp"
oc cp "${local_path}" "${namespace}"/"${pod_name}":/tmp

#unzip the files into the right place
echo "oc exec -n ${namespace} ${pod_name}  -- tar -xzf - /tmp/"${local_path}" -C "${remote_path}""
oc exec -n ${namespace} ${pod_name} -- tar -xzf /tmp/"${local_path}" -C "${remote_path}"

# Clean up tmp file
echo "oc exec -n ${namespace} ${pod_name} -- rm /tmp/"${local_path}""
oc exec -n ${namespace} ${pod_name} -- rm /tmp/"${local_path}"
