#!/bin/bash --norc
set -euo pipefail

name="$1"
timeout="$2"
target="$3"
shift 3

if ! [[ "$target" == //* ]]; then
  echo Must specify absolute target name >&2
  exit 1
fi

function target_to_executable() {
  executable="${1#//}"
  if [[ "$executable" == *:* ]]; then
    # Partition around ':' and join with '/'
    echo ${executable%:*}/${executable##*:}
  else
    # Repeat package basename for implicit target name
    echo $executable/$(basename "$executable")
  fi
}

export ZOOX_LOGGER_LEVEL=debug
export ZOOX_EXECUTION_NAMESPACE=mapping-backfill
export ZOOX_EXECUTION_NAME="$name"
export ZOOX_EXECUTION_ID=testing
export ZOOX_EXECUTION_TIME="$(date --utc +%Y-%m-%dT%H:%M:%S.%N-0000)"
export ZOOX_QUEUE_HOST=127.0.0.1
export ZOOX_QUEUE_PORT=6379
export ZOOX_QUEUE_KEY="$ZOOX_EXECUTION_NAMESPACE:$ZOOX_EXECUTION_NAME:$ZOOX_EXECUTION_ID"
export ZOOX_PROCESS_ATTEMPTS_MAX=1
export ZOOX_PROCESS_LEASE_S=300
export ZOOX_PROCESS_RENEW_S=60
export ZOOX_PROCESS_TIMEOUT_S="$timeout"
export ZOOX_REPORT_CLUSTER=https://search-ingest-heenk2pp6ah4o3j4y3rkqvim3a.us-west-2.es.amazonaws.com
export ZOOX_REPORT_INDEX="$ZOOX_EXECUTION_NAMESPACE--$ZOOX_EXECUTION_NAME"
export ZOOX_REPORT_TIMEOUT_S=2
export ZOOX_WORK_EXECUTABLE="$(target_to_executable "$target")"
export ZOOX_PROCESS_ARGUMENTS="$@"

# Build requisite targets.
workspace="$(bazel info workspace)"
bazel_bin="$(bazel info bazel-bin)"
bazel build //mapping/component/backfill/execute:worker "$target"

# Bind redis queue port.
kubectl port-forward deployment/execution 6379:6379 >/dev/null &
port_forward_pid="$!"

function onexit() {
  kill -INT "$port_forward_pid"
}
trap onexit EXIT

while ! (lsof -i -P -n | grep LISTEN | grep --quiet 6379) >&2; do
  # Wait for port to become bound.
  sleep 1
done

# Populate work queue.
echo Reading STDIN for work items >&2
xargs redis-cli lpush "$ZOOX_QUEUE_KEY" <&1

# Execute worker.
export BUILD_WORKING_DIRECTORY="$(pwd)"
export BUILD_WORKSPACE_DIRECTORY="$workspace"
builtin cd "$bazel_bin"
mapping/component/backfill/execute/worker
