#!/usr/bin/env bash
# Usage: rakazo-broker <endpoint> <json-payload>. Posts to the evOo GitHub broker and replays its output.
set -euo pipefail
endpoint="$1"
payload="$2"
post() {
  curl -fsS --connect-timeout 5 -X POST "$1/$endpoint" "${@:2}" \
    -H "Authorization: Bearer ${RAKAZO_GITHUB_BROKER_RUN_TOKEN}" \
    -H "Content-Type: application/json" \
    --data-binary "$payload"
}
# Computers created before host.docker.internal was mapped still reach the host on their default gateway.
gateway_url() {
  python3 -c '
import socket, struct, sys, urllib.parse
url = urllib.parse.urlsplit(sys.argv[1])
if url.hostname != "host.docker.internal":
    sys.exit(1)
for line in open("/proc/net/route").readlines()[1:]:
    fields = line.split()
    if fields[1] == "00000000":
        gateway = socket.inet_ntoa(struct.pack("<L", int(fields[2], 16)))
        print(url._replace(netloc=gateway + (f":{url.port}" if url.port else "")).geturl())
        sys.exit(0)
sys.exit(1)
' "$RAKAZO_GITHUB_BROKER_URL"
}
# Names each path that failed so the user can pass the exact cause on.
unreachable() {
  echo "evOo could not reach its GitHub connection from this computer (${attempts}curl exit $status). Tell the user GitHub access is broken on the evOo server and quote this line; do not ask for a token." >&2
  exit 1
}
status=0
attempts=""
socket=/run/rakazo-github-broker/broker.sock
if [[ -S "$socket" ]]; then
  response="$(post http://broker/internal/github-broker --unix-socket "$socket" 2>/dev/null)" || status=$?
  [[ "$status" == 0 ]] || attempts="socket exit $status; "
else
  attempts="no socket; "
fi
# 7: nothing listening on the socket either; then try the network.
if [[ ! -S "$socket" || "$status" == 7 ]]; then
  status=0
  response="$(post "$RAKAZO_GITHUB_BROKER_URL" 2>/dev/null)" || status=$?
fi
# 6: unresolved host, 7: connection refused, 28: timeout. Anything else is the broker answering.
if [[ "$status" == 6 || "$status" == 7 || "$status" == 28 ]]; then
  fallback="$(gateway_url)" || unreachable
  status=0
  response="$(post "$fallback" 2>/dev/null)" || status=$?
fi
if [[ "$status" == 22 ]]; then
  echo "evOo refused this GitHub request. Retry once; if it fails again, tell the user. Do not ask for a token." >&2
  exit 1
fi
[[ "$status" == 0 ]] || unreachable
code="$(python3 -c 'import json,sys; print(json.load(sys.stdin).get("code",1))' <<<"$response")"
python3 -c 'import json,sys; b=json.load(sys.stdin); sys.stdout.write(b.get("stdout") or ""); sys.stderr.write(b.get("stderr") or b.get("error") or "")' <<<"$response"
exit "$code"
