#!/bin/sh
set -eu

AUTH_ENDPOINT="${PROSODY_AUTH_ENDPOINT:-http://127.0.0.1:8000/internal/prosody/auth/}"
PROSODY_SECRET="${XMPP_SECRET:-}"

b64url() {
  printf '%s' "$1" | base64 | tr -d '\n=' | tr '+/' '-_'
}

http_get() {
  url="$1"
  if command -v wget >/dev/null 2>&1; then
    wget -qO- -T 5 "$url" 2>/dev/null
    return
  fi
  if command -v curl >/dev/null 2>&1; then
    curl -fsS --max-time 5 "$url" 2>/dev/null
    return
  fi
  if command -v lua >/dev/null 2>&1; then
    lua - "$url" <<'LUA'
local http = require("socket.http")
local ltn12 = require("ltn12")
http.TIMEOUT = 5
local chunks = {}
local _, code = http.request({
  url = arg[1],
  sink = ltn12.sink.table(chunks),
})
if tonumber(code) and tonumber(code) >= 200 and tonumber(code) < 300 then
  io.write(table.concat(chunks))
end
LUA
    return
  fi
  return 1
}

while IFS= read -r line; do
  if [ -z "$line" ] || [ -z "$PROSODY_SECRET" ]; then
    printf '0\n'
    continue
  fi
  secret_b64="$(b64url "$PROSODY_SECRET")"
  line_b64="$(b64url "$line")"
  result="$(http_get "$AUTH_ENDPOINT?secret_b64=$secret_b64&line_b64=$line_b64" || printf '0')"
  case "$result" in
    1|1$'\n')
      printf '1\n'
      ;;
    *)
      printf '0\n'
      ;;
  esac
done
