#!/bin/bash
set -euo pipefail

# Exec a file in the named component by component name and container name.
# Remaining arguments are passed to the command. If no static pods have been
# created yet this will execute on the host.
if [[ -z "${1-}" || -z "${2-}" ]]; then
  echo "A component name like 'api', 'etcd', or 'controllers' must be specified along with the container name within that component." 1>&2
  exit 1
fi

# We haven't started using static pods yet, assume this command is to be direct executed
if [[ ! -d /etc/origin/node/pods || -z "$( ls -A /etc/origin/node/pods )" ]]; then
  exec "${@:3}"
fi

# TODO: move to cri-ctl
# TODO: short term hack for cri-o

uid=$(docker ps -l -a --filter "label=openshift.io/component=${1}" --filter "label=io.kubernetes.container.name=POD" --format '{{ .Label "io.kubernetes.pod.uid" }}')
if [[ -z "${uid}" ]]; then
  echo "Component ${1} is stopped or not running" 1>&2
  exit 0
fi
container=$(docker ps -l -a -q --filter "label=io.kubernetes.pod.uid=${uid}" --filter "label=io.kubernetes.container.name=${2}")
exec docker exec "${container}" "${@:3}"